MagicObject\DataTable

Declaration

class DataTable extends MagicObject\SetterGetter { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class DataTable

Represents a data table for managing and rendering structured data. This class supports dynamic loading of data, multi-language support, and provides methods for manipulating the table's structure and appearance.

The DataTable class can be used to create HTML tables dynamically based on the provided data, with support for property annotations to manage labels and attributes.

Constants

const ANNOTATION_TABLE = "Table";
const ANNOTATION_ATTRIBUTES = "Attributes";
const CLASS_LIST = "ClassList";
const ANNOTATION_ID = "Id";
const ANNOTATION_COLUMN = "Column";
const ANNOTATION_VAR = "var";
const ANNOTATION_GENERATED_VALUE = "GeneratedValue";
const ANNOTATION_NOT_NULL = "NotNull";
const ANNOTATION_DEFAULT_COLUMN = "DefaultColumn";
const ANNOTATION_DEFAULT_COLUMN_LABEL = "DefaultColumnLabel";
const ANNOTATION_LANGUAGE = "Language";
const KEY_PROPERTY_TYPE = "property_type";
const KEY_PROPERTY_NAME = "property_name";
const KEY_NAME = "name";
const KEY_CLASS = "class";
const KEY_VALUE = "value";
const SQL_DATE_TIME_FORMAT = "Y-m-d H:i:s";
const DATE_TIME_FORMAT = "datetimeformat";
const TAG_TABLE = "table";
const TAG_THEAD = "thead";
const TAG_TBODY = "tbody";
const TAG_TR = "tr";
const TAG_TH = "th";
const TAG_TD = "td";
const TD_LABEL = "td-label";
const TD_VALUE = "td-value";

Properties

1. _currentLanguage

Declaration

private string $_currentLanguage;

Description

Current language code.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _lableLanguage

Declaration

private PicoLanguage[] $_lableLanguage = array();

Description

Language instances.

The property name starts with an underscore to prevent child classes from overriding its value.

3. _tableIdentity

Declaration

private PicoGenericObject $_tableIdentity;

Description

Table identity.

The property name starts with an underscore to prevent child classes from overriding its value.

4. _tableInfo

Declaration

private PicoTableInfo $_tableInfo;

Description

Table information.

The property name starts with an underscore to prevent child classes from overriding its value.

5. _labels

Declaration

private array $_labels = array();

Description

Labels for the table.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

3. addLanguage

Declaration

public function addLanguage(
    string $code,
    object|stdClass|array $reference,
    bool $use = false
) : self
{
}

Description

Adds a language to the table for multi-language support.

This method registers a language instance, which can be used to retrieve labels in the specified language.

Parameters

$code

Language code (e.g., 'en', 'fr').

$reference

Reference for language data.

$use

Indicates whether to set this language as the current one.

Return

self

Returns the current instance for method chaining.

4. removeLanguage

Declaration

public function removeLanguage(
    string $code
) : self
{
}

Description

Removes a specified language from the table.

If the removed language was the current one, the first remaining language will be selected as the new current language.

Parameters

$code

Language code to remove.

Return

self

Returns the current instance for method chaining.

5. selectLanguage

Declaration

public function selectLanguage(
    string $code
) : self
{
}

Description

Sets the current language for label retrieval.

This method updates the language code used for displaying labels.

Parameters

$code

Language code to set as current.

Return

self

Returns the current instance for method chaining.

6. init

Declaration

private function init() : self
{
}

Description

Initializes the table's attributes and configurations based on annotations.

This method parses the class annotations to set attributes, class lists, and preferred language settings.

Return

self

Returns the current instance for method chaining.

8. annotationContent

Declaration

private function annotationContent(
    PicoAnnotationParser $reflexProp,
    PicoGenericObject $parameters,
    string $annotation,
    string $attribute
) : mixed|null
{
}

Description

Retrieves the content of a specified annotation.

This method checks for the existence of an annotation and retrieves its attribute value if it exists.

Parameters

$reflexProp

Class reflection for parsing annotations.

$parameters

Parameters for the annotation.

$annotation

Annotation key to look up.

$attribute

Attribute key for the annotation value.

Return

mixed|null

The value of the annotation attribute or null if not found.

9. label

Declaration

private function label(
    PicoAnnotationParser $reflexProp,
    PicoGenericObject $parameters,
    string $key,
    string $defaultLabel
) : string
{
}

Description

Defines the label for a property based on its annotations.

This method retrieves and selects the appropriate label for a given property, falling back to default behavior if necessary.

Parameters

$reflexProp

Class reflection for property.

$parameters

Parameters associated with the property.

$key

Property key for which to retrieve the label.

$defaultLabel

Default label to use if no annotation is found.

Return

string

The determined label for the property.

10. appendByProp

Declaration

private function appendByProp(
    DOMDocument $doc,
    DOMNode $tbody,
    array $props,
    string $className
) : self
{
}

Description

Appends table rows based on class properties.

This method generates rows for the table based on the properties of the class and appends them to the provided DOM node.

Parameters

$doc

The DOM document used to create elements.

$tbody

The DOM node representing the of the table.

$props

Array of ReflectionProperty objects representing class properties.

$className

Name of the class for reflection.

Return

self
11. appendByValues

Declaration

private function appendByValues(
    DOMDocument $doc,
    DOMNode $tbody,
    stdClass $values
) : self
{
}

Description

Appends table rows based on provided values.

This method takes an array of values and creates rows in the table, appending them to the provided DOM node.

Parameters

$doc

The DOM document used to create elements.

$tbody

The DOM node representing the of the table.

$values

Data to append as rows.

Return

self
12. getLabel

Declaration

private function getLabel(
    string $propertyName
) : string
{
}

Description

Gets the label for a specified property.

This method retrieves the label associated with a property, checking for language-specific labels before falling back to default labels.

Parameters

$propertyName

Name of the property for which to retrieve the label.

Return

string

The label for the specified property.

13. addClass

Declaration

public function addClass(
    string $className
) : self
{
}

Description

Adds a CSS class to the table.

This method appends a class to the table's class list, ensuring that there are no duplicates.

Parameters

$className

Class name to add to the table.

Return

self

Returns the current instance for method chaining.

14. removeClass

Declaration

public function removeClass(
    string $className
) : self
{
}

Description

Removes a CSS class from the table.

This method filters out the specified class from the table's class list.

Parameters

$className

Class name to remove from the table.

Return

self

Returns the current instance for method chaining.

15. replaceClass

Declaration

public function replaceClass(
    string $search,
    string $replace
) : self
{
}

Description

Replaces a class in the table with a new class name.

Parameters

$search

Class name to search for.

$replace

Class name to replace with.

Return

self

Returns the current instance for method chaining.

17. getTableInfo

Declaration

public function getTableInfo() : PicoTableInfo
{
}

Description

Gets table information.

Return

PicoTableInfo

MagicObject\Getter

Declaration

class Getter extends stdClass { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class Getter

This class provides dynamic property access and management for instances of the MagicObject framework. It allows for loading data into an object from various formats and supports retrieving property values, including handling naming conventions and formatting for JSON output.

Key Features:

  • Dynamically load data from associative arrays or objects.
  • Retrieve property values using both explicit getter methods and dynamic method calls.
  • Convert object properties into a structured representation suitable for JSON encoding.
  • Support for property naming strategies (snake case and pretty formatting) for JSON output.

Constants

const JSON = "JSON";

Properties

1. _classParams

Declaration

private array $_classParams = array();

Description

Class parameters that configure behavior such as JSON output formatting.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

1. __construct

Declaration

public function __construct()
{
}

Description

Constructor that initializes class parameters based on annotations.

2. loadData

Declaration

public function loadData(
    stdClass|array $data
)
{
}

Description

Load data into the object.

Parameters

$data

Data to load, which can be an associative array or object.

3. get

Declaration

public function get(
    string $propertyName
) : mixed|null
{
}

Description

Get the value of a specified property.

Parameters

$propertyName

Name of the property to retrieve.

Return

mixed|null

The value of the property, or null if not set.

4. value

Declaration

public function value(
    bool $snakeCase = false
) : stdClass|array
{
}

Description

Retrieve all properties as a structured object or array.

Parameters

$snakeCase

If true, convert property names to snake case.

Return

stdClass|array

The object containing property values, or an array if snakeCase is true.

5. propertyList

Declaration

protected function propertyList(
    bool $reflectSelf = false,
    bool $asArrayProps = false
) : array|ReflectionProperty[]
{
}

Description

List properties of the current object.

Parameters

$reflectSelf

If true, include properties declared in this class.

$asArrayProps

If true, return properties as an array of strings.

Return

array|ReflectionProperty[]

List of properties or an array of property names.

6. __call

Declaration

public function __call(
    string $method,
    array $params
) : mixed|null
{
}

Description

Magic method for handling calls to undefined methods.

Parameters

$method

Name of the called method.

$params

Parameters passed to the method.

Return

mixed|null

The result of the method call, if applicable.

7. isSnake

Declaration

private function isSnake() : bool
{
}

Description

Check if the JSON naming strategy is snake case.

Return

bool

True if the naming strategy is snake case, false otherwise.

8. isPretty

Declaration

private function isPretty() : bool
{
}

Description

Determine if JSON output should be prettified.

Return

bool

True if prettification is enabled, false otherwise.

9. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation.

Return

string

A JSON representation of the object, formatted based on the naming strategy.

MagicObject\MagicDto

Declaration

class MagicDto extends stdClass { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class MagicDto

Represents a dynamic data transfer object that allows the user to create and manipulate properties on-the-fly. It can handle various data sources including INI, YAML, JSON, and databases. Users can perform CRUD operations on database records and manipulate properties as needed.

Constants

const JSON = "JSON";
const XML = "XML";
const PRETTIFY = "prettify";

Properties

1. _classParams

Declaration

private array $_classParams = array();

Description

Class parameters.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _dataSource

Declaration

private mixed $_dataSource;

Description

Data source.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

1. __construct

Declaration

public function __construct(
    self|array|stdClass|MagicObject|SetterGetter|SecretObject|PicoGenericObject|null $data = null
)
{
}

Description

Constructor.

Initializes the object with provided data and database connection.

Parameters

$data

Initial data to populate the object.

2. onLoadData

Declaration

public function onLoadData(
    mixed $object
) : mixed
{
}

Description

Before loading data.

This method is called before loading data into the object. Users can override this method to manipulate the object as needed.

Parameters

$object

The object to manipulate before loading data.

Return

mixed

The manipulated object.

3. loadData

Declaration

public function loadData(
    self|array|stdClass|MagicObject|SetterGetter|SecretObject|PicoGenericObject|null $data
) : self
{
}

Description

Loads data into the object.

This method accepts various data types, including:

  • An instance of the class itself
  • An array
  • A standard object (stdClass)
  • Other specific object types such as MagicObject, SetterGetter, SecretObject, and PicoGenericObject.

    The method processes the input data and stores it in the internal data source of the object, ensuring that only non-scalar values are handled.

Parameters

$data

Return

self

Returns the current instance for method chaining.

4. loadXml

Declaration

public function loadXml(
    string $xmlString
) : self
{
}

Description

Loads XML data into the object.

This method accepts an XML string, converts it to an object representation, and then loads the resulting data into the internal data source of the object. It processes the XML input, ensuring that only non-scalar values are handled appropriately. This method is useful for integrating with external XML data sources.

Parameters

$xmlString

The XML string to load into the object.

Return

self

Returns the current instance for method chaining.

Throws

InvalidArgumentException

If the XML string is invalid or cannot be parsed.

5. value

Declaration

public function value() : stdClass
{
}

Description

Retrieves an object containing the values of the properties of the current instance.

This method iterates through the properties of the instance, excluding inherited properties, and constructs an object where each property is mapped to its corresponding value. The method handles various property types including self-references, magic objects, DateTime instances, and standard class objects.

Return

stdClass

An object containing the values of the properties, where each property

6. createTestObject

Declaration

private function createTestObject(
    string $var
) : mixed|null
{
}

Description

Creates an instance of a class based on the provided variable name.

This method checks if the class corresponding to the given variable name exists. If it does, an instance of that class is created and returned; otherwise, null is returned.

Parameters

$var

The name of the class to instantiate.

Return

mixed|null

An instance of the class if it exists, or null if the class does not exist.

7. formatDateTime

Declaration

private function formatDateTime(
    DateTime|null $dateTime,
    object $class,
    string $property
) : string|null
{
}

Description

Formats a DateTime object according to specified JSON format parameters.

This method checks if the provided DateTime object is set and, if so, retrieves formatting parameters from the property's annotations. If a 'JsonFormat' parameter is present, its pattern is used; otherwise, a default format of 'Y-m-d H:i:s' is applied.

Parameters

$dateTime

The DateTime object to format.

$class

The class instance from which the property originates.

$property

The name of the property being processed.

Return

string|null

The formatted date as a string, or null if the DateTime is not set.

8. parseDateTime

Declaration

private function parseDateTime(
    string|int $dateString
) : DateTime|null
{
}

Description

Parse DateTime from a string or Unix timestamp.

This method attempts to parse a given date string or Unix timestamp into a DateTime object using multiple predefined formats. If the parsing is successful, it returns the corresponding DateTime object; otherwise, it returns null.

Parameters

$dateString

The date string or Unix timestamp to be parsed.

Return

DateTime|null

Returns a DateTime object if parsing is successful,

9. getPropertyDocComment

Declaration

private function getPropertyDocComment(
    string $key
) : string|null
{
}

Description

Retrieves the documentation comment for a specified property.

Parameters

$key

The name of the property.

Return

string|null

The documentation comment for the property, or null if not found.

10. extractSource

Declaration

private function extractSource(
    string $doc
) : string|null
{
}

Description

Extracts the source from the documentation comment.

Parameters

$doc

The documentation comment containing the source.

Return

string|null

The extracted source or null if not found.

11. extractJsonProperty

Declaration

private function extractJsonProperty(
    string $doc
) : string|null
{
}

Description

Extracts the JSON property name from the documentation comment.

Parameters

$doc

The documentation comment containing the JSON property.

Return

string|null

The extracted JSON property name or null if not found.

12. extractVar

Declaration

private function extractVar(
    string $doc
) : string|null
{
}

Description

Extracts the variable type from the documentation comment.

Parameters

$doc

The documentation comment containing the variable type.

Return

string|null

The extracted variable type or null if not found.

13. extractLabel

Declaration

private function extractLabel(
    string $doc
) : string|null
{
}

Description

Extracts the label from the documentation comment.

Parameters

$doc

The documentation comment containing the label.

Return

string|null

The extracted label or null if not found.

14. handleSelfInstance

Declaration

private function handleSelfInstance(
    string|null $source,
    string $var,
    string $propertyName
) : mixed
{
}

Description

Handles the case where the property is a self-instance.

This method retrieves the value from the data source based on the provided source or property name. If the source indicates a nested property, it retrieves that value instead. It constructs an instance of the specified class type and returns its stringified value.

Parameters

$source

The source to extract the value from.

$var

The variable type (class name) to instantiate.

$propertyName

The name of the property to fall back on.

Return

mixed

The handled value for the self-instance.

15. isSelfInstance

Declaration

private function isSelfInstance(
    mixed $objectTest
) : bool
{
}

Description

Checks if the given variable is a self-instance.

Parameters

$objectTest

The object to test against.

Return

bool

True if it's a self-instance, otherwise false.

16. isMagicObjectInstance

Declaration

private function isMagicObjectInstance(
    mixed $objectTest
) : bool
{
}

Description

Checks if the given object is an instance of MagicObject or its derivatives.

Parameters

$objectTest

The object to test.

Return

bool

True if it is a MagicObject instance, otherwise false.

17. isDateTimeInstance

Declaration

private function isDateTimeInstance(
    mixed $objectTest
) : bool
{
}

Description

Checks if the given object is an instance of DateTime or its derivatives.

Parameters

$objectTest

The object to test.

Return

bool

True if it is a MagicObject instance, otherwise false.

18. handleMagicObject

Declaration

private function handleMagicObject(
    string|null $source,
    string $propertyName
) : mixed
{
}

Description

Handles the case where the property is an instance of MagicObject.

This method retrieves the value from the data source and checks if it is an instance of MagicObject or its derivatives. If so, it returns the stringified value; otherwise, it returns a JSON-encoded version.

Parameters

$source

The source to extract the value from.

$propertyName

The name of the property.

Return

mixed

The handled value for the MagicObject instance.

19. handleDateTimeObject

Declaration

private function handleDateTimeObject(
    string|null $source,
    string $propertyName
) : DateTime|null
{
}

Description

Handles the case where the property is an instance of DateTime.

This method retrieves the value from the data source and parses it into a DateTime object, either from the source or a nested value.

Parameters

$source

The source to extract the value from.

$propertyName

The name of the property.

Return

DateTime|null

The handled DateTime value or null if not applicable.

20. handleDefaultCase

Declaration

private function handleDefaultCase(
    string|null $source,
    string $key
) : mixed
{
}

Description

Handles the default case when retrieving property values.

This method delegates the handling of standard class properties to another method.

Parameters

$source

The source to extract the value from.

$key

The key of the property.

Return

mixed

The handled default value.

21. handleStdClass

Declaration

private function handleStdClass(
    string|null $source,
    string $key
) : mixed
{
}

Description

Handles the stdClass when retrieving property values.

This method retrieves the value from the data source based on the given source or key, accounting for nested properties if necessary.

Parameters

$source

The source to extract the value from.

$key

The key of the property.

Return

mixed

The retrieved value or null if not found.

22. getNestedValue

Declaration

private function getNestedValue(
    string $source
) : mixed
{
}

Description

Retrieves nested values from the data source based on a specified source string.

This method splits the source string by the "->" delimiter to navigate through nested properties in the data source, returning the final nested value found.

Parameters

$source

The source string indicating the path to the value.

Return

mixed

The nested value retrieved from the data source, or null if not found.

23. valueObject

Declaration

public function valueObject() : stdClass
{
}

Description

Get the object value as a specified format.

This method creates a clone of the current object and transforms its properties into a value representation, returning the object as an instance of stdClass.

Return

stdClass

An object representing the value of the instance.

24. valueArray

Declaration

public function valueArray() : array
{
}

Description

Get the object value as an associative array.

This method converts the object's value representation into an associative array.

Return

array

An associative array representing the object values.

25. valueArrayUpperCamel

Declaration

public function valueArrayUpperCamel() : array
{
}

Description

Get the object value as an associative array with the first letter of each key in upper camel case.

This method transforms the keys of the associative array representation of the object values to be in upper camel case format.

Return

array

An associative array with keys in upper camel case.

26. _prettyJson

Declaration

protected function _prettyJson() : bool
{
}

Description

Check if the JSON output should be prettified.

This method checks the class parameters to determine if JSON output formatting should be applied to enhance readability.

Return

bool

True if JSON output is set to be prettified; otherwise, false.

27. _prettyXml

Declaration

protected function _prettyXml() : bool
{
}

Description

Check if the XML output should be prettified.

This method checks the class parameters to determine if XML output formatting should be applied to enhance readability.

Return

bool

True if XML output is set to be prettified; otherwise, false.

28. propertyList

Declaration

protected function propertyList(
    bool $reflectSelf = false,
    bool $asArrayProps = false
) : array
{
}

Description

Retrieves a list of properties from the current class or its parent class.

This method uses reflection to obtain the properties defined in the class. It can return either the property names as an array or the ReflectionProperty objects, depending on the specified flags.

Parameters

$reflectSelf

Flag indicating whether to reflect properties of the current class (true) or the parent class (false).

$asArrayProps

Flag indicating whether to return property names as an array (true) or as ReflectionProperty objects (false).

Return

array

An array of property names or ReflectionProperty objects, based on the provided flags.

29. stringifyObject

Declaration

private function stringifyObject(
    self|array $value
) : mixed
{
}

Description

Recursively converts an object or an array of objects to their string representation.

This method traverses through an object or an array of objects of the same class and calls their respective stringify methods, if applicable. The final output is the stringified representation of the object or array.

Parameters

$value

The object or array of objects to stringify.

Return

mixed

The stringified object or array.

30. xmlToObject

Declaration

public function xmlToObject(
    string $xmlString
) : stdClass
{
}

Description

Convert XML to an object.

This function takes an XML string as input and returning it as a stdClass object.

Parameters

$xmlString

The XML string to be converted.

Return

stdClass

An object representation of the XML data.

Throws

InvalidArgumentException

If the XML is invalid or cannot be parsed.

31. __toString

Declaration

public function __toString() : string
{
}

Description

Magic method to convert the object to a JSON string representation.

This method recursively converts the object's properties into JSON format. If any property is an instance of the same class, it will also be stringified. The output can be formatted for readability based on the JSON annotation of the class.

Return

string

A JSON representation of the object, potentially formatted for readability.

32. toString

Declaration

public function toString() : string
{
}

Description

Magic method to convert the object to a JSON string representation.

This method recursively converts the object's properties into JSON format. If any property is an instance of the same class, it will also be stringified. The output can be formatted for readability based on the JSON annotation of the class.

Return

string

A JSON representation of the object, potentially formatted for readability.

33. toJson

Declaration

public function toJson() : object|null
{
}

Description

Convert the object to a JSON object.

This method decodes the JSON string representation of the object (produced by the __toString() method) and returns it as a PHP object. This is useful for working with the data in a more structured format rather than as a JSON string.

Return

object|null

A PHP object representation of the JSON data, or null if decoding fails.

34. toArray

Declaration

public function toArray() : array|null
{
}

Description

Convert the object to an associative array.

This method decodes the JSON string representation of the object (produced by the __toString() method) and returns it as an associative array. This is useful for accessing the object's properties in a more straightforward array format.

Return

array|null

An associative array representation of the JSON data, or null if decoding fails.

35. toXml

Declaration

public function toXml(
    string $root = 'root'
) : string
{
}

Description

Convert the object's properties to XML format.

This method generates an XML representation of the object based on its properties. The XML structure is built from the object's properties, and the output can be formatted for readability based on the XML annotation of the class.

Parameters

$root

The name of the root element in the XML structure.

Return

string

XML representation of the object's properties, potentially formatted for readability.

Throws

InvalidArgumentException

If the JSON representation of the object is invalid.

36. arrayToXml

Declaration

public function arrayToXml(
    array $dataArray,
    SimpleXMLElement $xml
) : void
{
}

Description

Converts an array to XML format and appends it to a SimpleXMLElement.

This function takes an associative or indexed array and recursively converts it into XML elements. Keys in the array are sanitized to ensure they are valid XML element names. Values that are not arrays are added as child elements.

Parameters

$dataArray

The array to convert to XML.

$xml

The XML element to which the converted data will be appended.

Return

void

This function does not return a value. It modifies the provided XML element.

37. isMethodOverridden

Declaration

private function isMethodOverridden(
    string $childClass,
    string $methodName
) : bool
{
}

Description

Check if a method is overridden in a child class.

This method uses reflection to determine if a given method is overridden in the specified child class. It compares the methods of the child class with those of its parent class, checking if the method is present in both classes but has been redefined in the child class.

Parameters

$childClass

The child class name or instance to check for method override.

$methodName

The name of the method to check for overriding.

Return

bool

Returns true if the method is overridden in the child class, false otherwise.

MagicObject\MagicObject

Declaration

class MagicObject extends stdClass { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for creating a magic object. A magic object is an instance created from any class, allowing the user to add any property with any name and value. It can load data from INI files, YAML files, JSON files, and databases. Users can create entities from database tables and perform insert, select, update, and delete operations on records in the database. Users can also create properties from other entities using the full name of the class (namespace + class name).

Constants

const MESSAGE_NO_DATABASE_CONNECTION = "No database connection provided";
const MESSAGE_NO_RECORD_FOUND = "No record found";
const PROPERTY_NAMING_STRATEGY = "property-naming-strategy";
const PROPERTY_NAMING_STRATEGY_CAMEL = "propertyNamingStrategy";
const KEY_PROPERTY_TYPE = "propertyType";
const KEY_NAME = "name";
const KEY_VALUE = "value";
const KEY_TYPE = "type";
const KEY_LENGTH = "length";
const KEY_DEFAULT_VALUE = "defaultValue";
const JSON = "JSON";
const YAML = "Yaml";
const ATTR_CHECKED = " checked="checked"";
const ATTR_SELECTED = " selected="selected"";
const FIND_OPTION_DEFAULT = 0;
const FIND_OPTION_NO_COUNT_DATA = 1;
const FIND_OPTION_NO_FETCH_DATA = 2;
const SNAKE_CASE = "SNAKE_CASE";
const UPPER_CAMEL_CASE = "UPPER_CAMEL_CASE";

Properties

1. _readonly

Declaration

private bool $_readonly = false;

Description

Indicates whether the object is read-only.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _database

Declaration

private PicoDatabase $_database;

Description

Database connection instance.

The property name starts with an underscore to prevent child classes from overriding its value.

3. _databaseEntity

Declaration

private PicoDatabaseEntity $_databaseEntity;

Description

Class containing a database entity.

The property name starts with an underscore to prevent child classes from overriding its value.

4. _classParams

Declaration

private array $_classParams = array();

Description

Class parameters.

The property name starts with an underscore to prevent child classes from overriding its value.

5. _nullProperties

Declaration

private array $_nullProperties = array();

Description

List of null properties.

The property name starts with an underscore to prevent child classes from overriding its value.

6. _label

Declaration

private array $_label = array();

Description

Property labels.

The property name starts with an underscore to prevent child classes from overriding its value.

7. _tableInfoProp

Declaration

private PicoTableInfo $_tableInfoProp;

Description

Table information instance.

The property name starts with an underscore to prevent child classes from overriding its value.

8. _persistProp

Declaration

private PicoDatabasePersistence $_persistProp;

Description

Database persistence instance.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

1. nullPropertyList

Declaration

public function nullPropertyList() : array
{
}

Description

Retrieves the list of null properties.

Return

array

The list of properties that are currently null.

2. __construct

Declaration

public function __construct(
    self|array|stdClass|object|null $data = null,
    PicoDatabase|PDO|null $database = null
)
{
}

Description

Constructor.

Initializes the object with the provided data and optionally connects to a database. The constructor can accept different types of data to populate the object and can also accept a PDO connection or a PicoDatabase instance to set up the database connection.

Parameters

$data

Initial data to populate the object. This can be:

$database

A database connection instance, either:

Throws

InvalidAnnotationException

If the annotations are invalid or cannot be parsed.

3. loadData

Declaration

public function loadData(
    mixed $data
) : self
{
}

Description

Loads data into the object.

Parameters

$data

Data to load, which can be another MagicObject, an array, or an object.

Return

self

Returns the current instance for method chaining.

4. loadIniString

Declaration

public function loadIniString(
    string $rawData,
    bool $systemEnv = false
) : self
{
}

Description

Load data from an INI string.

Parameters

$rawData

Raw INI data

$systemEnv

Flag to indicate whether to use environment variables

Return

self

Returns the current instance for method chaining.

5. loadIniFile

Declaration

public function loadIniFile(
    string $path,
    bool $systemEnv = false
) : self
{
}

Description

Load data from an INI file.

Parameters

$path

File path to the INI file

$systemEnv

Flag to indicate whether to use environment variables

Return

self

Returns the current instance for method chaining.

6. loadYamlString

Declaration

public function loadYamlString(
    string $rawData,
    bool $systemEnv = false,
    bool $asObject = false,
    bool $recursive = false
) : self
{
}

Description

Load data from a YAML string.

Parameters

$rawData

YAML string

$systemEnv

Replace all environment variable values

$asObject

Result as an object instead of an array

$recursive

Convert all objects to MagicObject

Return

self

Returns the current instance for method chaining.

7. loadYamlFile

Declaration

public function loadYamlFile(
    string $path,
    bool $systemEnv = false,
    bool $asObject = false,
    bool $recursive = false
) : self
{
}

Description

Load data from a YAML file.

Parameters

$path

File path to the YAML file

$systemEnv

Replace all environment variable values

$asObject

Result as an object instead of an array

$recursive

Convert all objects to MagicObject

Return

self

Returns the current instance for method chaining.

8. loadJsonString

Declaration

public function loadJsonString(
    string $rawData,
    bool $systemEnv = false,
    bool $asObject = false,
    bool $recursive = false
) : self
{
}

Description

Load data from a JSON string.

Parameters

$rawData

JSON string

$systemEnv

Replace all environment variable values

$asObject

Result as an object instead of an array

$recursive

Convert all objects to MagicObject

Return

self

Returns the current instance for method chaining.

9. loadJsonFile

Declaration

public function loadJsonFile(
    string $path,
    bool $systemEnv = false,
    bool $asObject = false,
    bool $recursive = false
) : self
{
}

Description

Loads data from a JSON file and processes it based on the provided options.

Parameters

$path

The file path to the JSON file.

$systemEnv

Whether to replace system environment variables in the data (default: false).

$asObject

Whether to return the result as an object instead of an associative array (default: false).

$recursive

Whether to recursively convert all objects into MagicObject instances (default: false).

Return

self

Returns the current instance for method chaining.

Throws

FileNotFoundException

If the specified JSON file does not exist.

10. loadJsonData

Declaration

private function loadJsonData(
    mixed $data,
    bool $asObject,
    bool $recursive
) : self
{
}

Description

Loads processed JSON data and optionally converts it to objects or parses recursively.

Parameters

$data

The processed data to load (array or object).

$asObject

Whether to return the result as an object.

$recursive

Whether to recursively convert all objects into MagicObject instances.

Return

self

Returns the current instance for method chaining.

11. readOnly

Declaration

protected function readOnly(
    bool $readonly
) : self
{
}

Description

Set the read-only state of the object.

When set to read-only, setters will not change the value of its properties, but loadData will still function normally.

Parameters

$readonly

Flag to set the object as read-only

Return

self

Returns the current instance for method chaining.

12. _databaseConnected

Declaration

private function _databaseConnected() : bool
{
}

Description

Check if database is connected or not

Return

bool

Returns true if the database is connected, false otherwise.

13. withDatabase

Declaration

public function withDatabase(
    PicoDatabase $database
) : self
{
}

Description

Set the database connection.

Parameters

$database

Database connection

Return

self

Returns the current instance for method chaining.

14. currentDatabase

Declaration

public function currentDatabase(
    PicoDatabase|null $database = null
) : PicoDatabase|null
{
}

Description

Set or get the current database connection.

If the parameter is not empty, set the current database to the provided value. Otherwise, return the current database or null.

Parameters

$database

Database connection

Return

PicoDatabase|null
15. databaseEntity

Declaration

public function databaseEntity(
    MagicObject|PicoDatabaseEntity|null $databaseEntity = null
) : self|PicoDatabaseEntity
{
}

Description

Set or get the database entity.

If a database entity is provided, it will be set; otherwise, the current database entity will be returned.

Parameters

$databaseEntity

The database entity to set or null to get the current entity.

Return

self|PicoDatabaseEntity

Returns the current instance for method chaining, or the current database entity if no parameter is provided.

16. removePropertyExcept

Declaration

public function removePropertyExcept(
    object|array $sourceData,
    array $propertyNames
) : object|array
{
}

Description

Remove properties except for the specified ones.

Parameters

$sourceData

Data to filter

$propertyNames

Names of properties to retain

Return

object|array

Filtered data

17. save

Declaration

public function save(
    bool $includeNull = false
) : PDOStatement
{
}

Description

Save the current object to the database.

This method persists the current object to the database. If $includeNull is TRUE, all properties of the object, including those with null values, will be saved. If FALSE, only the properties with non-null values will be saved.

Parameters

$includeNull

If TRUE, all properties, including null, will be saved.

Return

PDOStatement

Returns a PDOStatement object for further database interaction.

Throws

NoDatabaseConnectionException

If there is no active database connection.

NoRecordFoundException

If no corresponding record is found.

PDOException

If a database error occurs.

18. saveQuery

Declaration

public function saveQuery(
    bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}

Description

Generate a query to save data to the database.

This method prepares a query to persist the current object to the database. If $includeNull is TRUE, properties with null values will be included in the query. If FALSE, only properties with non-null values will be included.

Parameters

$includeNull

If TRUE, all properties, including null, will be saved.

Return

PicoDatabaseQueryBuilder

Returns a PicoDatabaseQueryBuilder object for query construction.

Throws

NoDatabaseConnectionException

If there is no active database connection.

NoRecordFoundException

If no corresponding record is found.

19. select

Declaration

public function select() : self
{
}

Description

Select data from the database.

This method retrieves data from the database. If no data is found, a NoRecordFoundException will be thrown. The retrieved data is then loaded into the current instance for further use.

Return

self

Returns the current instance for method chaining.

Throws

NoDatabaseConnectionException

If there is no active database connection.

NoRecordFoundException

If no records are found in the database.

PDOException

If a database error occurs.

20. selectAll

Declaration

public function selectAll() : self
{
}

Description

Select all data from the database.

This method retrieves all data from the database. If no data is found, a NoRecordFoundException will be thrown. The retrieved data is then loaded into the current instance for further use.

Return

self

Returns the current instance for method chaining.

Throws

NoDatabaseConnectionException

If there is no active database connection.

NoRecordFoundException

If no records are found in the database.

PDOException

If a database error occurs.

21. selectQuery

Declaration

public function selectQuery() : PicoDatabaseQueryBuilder
{
}

Description

Generate a query to select data.

This method prepares a query to select data from the database. The query can then be used to execute the retrieval of data manually if needed.

Return

PicoDatabaseQueryBuilder

Returns a PicoDatabaseQueryBuilder object for building the select query.

Throws

NoDatabaseConnectionException

If there is no active database connection.

PDOException

If a database error occurs.

22. executeNativeQuery

Declaration

protected function executeNativeQuery() : mixed
{
}

Description

Executes a database query based on the parameters and annotations from the caller function.

This method uses reflection to extract the query string and return type from the caller's docblock, binds the provided parameters, and executes the query against the database.

It analyzes the parameters and return type of the caller function to enable dynamic query execution tailored to the specified return type. Supported return types include:

  • void: Returns null.
  • int or integer: Returns the number of affected rows.
  • object or stdClass: Returns a single result as an object.
  • stdClass[]: Returns all results as an array of stdClass objects.
  • array: Returns all results as an associative array.
  • string: Returns the JSON-encoded results.
  • PDOStatement: Returns the prepared statement for further operations if needed.
  • MagicObject and its derived classes: If the return type is a class name or an array of class names, instances of that class will be created for each row fetched.
  • MagicObject[] and its derived classes: Instances of the corresponding class will be created for each row fetched.

Return

mixed

The result based on the return type of the caller function:

Throws

PDOException

If there is an error executing the database query.

InvalidQueryInputException

If there is no query to be executed or if the input is invalid.

InvalidReturnTypeException

If the return type specified in the docblock is invalid or unrecognized.

23. insert

Declaration

public function insert(
    bool $includeNull = false
) : PDOStatement
{
}

Description

Insert data into the database.

This method inserts the current objectΓÇÖs data into the database. If $includeNull is TRUE, properties with null values will also be included in the insert query. If FALSE, only properties with non-null values will be inserted.

Parameters

$includeNull

If TRUE, all properties, including null, will be inserted. If FALSE, only non-null values will be inserted.

Return

PDOStatement

Returns a PDOStatement object for further database interaction.

Throws

NoDatabaseConnectionException

If there is no active database connection.

PDOException

If there is an error executing the insert query.

24. insertQuery

Declaration

public function insertQuery(
    bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}

Description

Get the query for inserting data.

This method prepares a query to insert data into the database. It can be used to manually execute the query. If $includeNull is TRUE, properties with null values will be included in the query. If FALSE, only non-null properties will be inserted.

Parameters

$includeNull

If TRUE, all properties, including null, will be included in the insert query. If FALSE, only non-null properties will be included.

Return

PicoDatabaseQueryBuilder

Returns a PicoDatabaseQueryBuilder object for building the insert query.

Throws

NoDatabaseConnectionException

If there is no active database connection.

25. update

Declaration

public function update(
    bool $includeNull = false
) : PDOStatement
{
}

Description

Update data in the database.

This method updates the current object's data in the database. If $includeNull is TRUE, properties with null values will be included in the update query. If FALSE, only properties with non-null values will be updated.

Parameters

$includeNull

If TRUE, all properties, including null, will be updated. If FALSE, only non-null values will be updated.

Return

PDOStatement

Returns a PDOStatement object for further database interaction.

Throws

NoDatabaseConnectionException

If there is no active database connection.

PDOException

If there is an error executing the update query.

26. updateQuery

Declaration

public function updateQuery(
    bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}

Description

Get the query for updating data.

This method prepares a query to update data in the database. It can be used to manually execute the query. If $includeNull is TRUE, properties with null values will be included in the update query. If FALSE, only non-null properties will be updated.

Parameters

$includeNull

If TRUE, all properties, including null, will be included in the update query. If FALSE, only non-null properties will be included.

Return

PicoDatabaseQueryBuilder

Returns a PicoDatabaseQueryBuilder object for building the update query.

Throws

NoDatabaseConnectionException

If there is no active database connection.

27. delete

Declaration

public function delete() : PDOStatement
{
}

Description

Delete data from the database.

This method deletes data associated with the current object from the database.

Return

PDOStatement

Returns a PDOStatement object for further database interaction.

Throws

NoDatabaseConnectionException

If there is no active database connection.

PDOException

If there is an error executing the delete query.

28. deleteQuery

Declaration

public function deleteQuery() : PicoDatabaseQueryBuilder
{
}

Description

Get the query for deleting data.

This method prepares a query to delete data from the database. It can be used to manually execute the query.

Return

PicoDatabaseQueryBuilder

Returns a PicoDatabaseQueryBuilder object for building the delete query.

Throws

NoDatabaseConnectionException

If there is no active database connection.

29. startTransaction

Declaration

public function startTransaction() : self
{
}

Description

Starts a database transaction.

This method begins a new database transaction. It delegates the actual transaction initiation to the transactionalCommand method, passing the "start" command.

Return

self

Returns the current instance for method chaining.

Throws

NoDatabaseConnectionException

If there is no active database connection.

PDOException

If there is an error while starting the transaction.

30. commit

Declaration

public function commit() : self
{
}

Description

Commits the current database transaction.

This method commits the current transaction. If successful, it makes all database changes made during the transaction permanent. It delegates to the transactionalCommand method with the "commit" command.

Return

self

Returns the current instance for method chaining.

Throws

NoDatabaseConnectionException

If there is no active database connection.

PDOException

If there is an error during the commit process.

31. rollback

Declaration

public function rollback() : self
{
}

Description

Rolls back the current database transaction.

This method rolls back the current transaction, undoing all database changes made during the transaction. It calls the transactionalCommand method with the "rollback" command.

Return

self

Returns the current instance for method chaining.

Throws

NoDatabaseConnectionException

If there is no active database connection.

PDOException

If there is an error during the rollback process.

32. where

Declaration

public function where(
    PicoSpecification $specification
) : PicoDatabasePersistenceExtended
{
}

Description

Get a MagicObject with a WHERE specification.

This method applies a WHERE condition to the database query using the provided specification. The specification is an instance of PicoSpecification which defines the filtering criteria.

Parameters

$specification

The specification to define the WHERE condition.

Return

PicoDatabasePersistenceExtended

Returns an instance of PicoDatabasePersistenceExtended

Throws

NoDatabaseConnectionException

If there is no active database connection.

33. modifyNullProperties

Declaration

private function modifyNullProperties(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Modify properties with null values.

This method tracks properties that are assigned a null value, storing them in a _nullProperties array. If a property is set to null, it is added to the _nullProperties array; if it's set to a non-null value, it is removed from the array.

Parameters

$propertyName

The name of the property to check and modify.

$propertyValue

The value to be assigned to the property.

Return

self

Returns the current instance for method chaining.

34. set

Declaration

public function set(
    string $propertyName,
    mixed|null $propertyValue,
    bool $skipModifyNullProperties = false
) : self
{
}

Description

Set property value.

Parameters

$propertyName

Property name

$propertyValue

Property value

$skipModifyNullProperties

Skip modifying null properties

Return

self

Returns the current instance for method chaining.

35. push

Declaration

public function push(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Adds an element to the end of an array property.

Parameters

$propertyName

Property name

$propertyValue

Property value

Return

self

Returns the current instance for method chaining.

36. append

Declaration

public function append(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Adds an element to the end of an array property (alias for push).

Parameters

$propertyName

Property name

$propertyValue

Property value

Return

self

Returns the current instance for method chaining.

37. unshift

Declaration

public function unshift(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Adds an element to the beginning of an array property.

Parameters

$propertyName

Property name

$propertyValue

Property value

Return

self

Returns the current instance for method chaining.

38. prepend

Declaration

public function prepend(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Adds an element to the beginning of an array property (alias for unshift).

Parameters

$propertyName

Property name

$propertyValue

Property value

Return

self

Returns the current instance for method chaining.

39. pop

Declaration

public function pop(
    string $propertyName
) : mixed
{
}

Description

Remove and return the last element of an array property.

This method removes the last element from an array property and returns it. If the specified property is not an array or does not exist, null is returned.

Parameters

$propertyName

The name of the property (array) from which the last element will be removed.

Return

mixed

The last element of the array, or null if the property is not an array or doesn't exist.

40. shift

Declaration

public function shift(
    string $propertyName
) : mixed
{
}

Description

Remove and return the first element of an array property.

This method removes the first element from an array property and returns it. If the specified property is not an array or does not exist, null is returned.

Parameters

$propertyName

The name of the property (array) from which the first element will be removed.

Return

mixed

The first element of the array, or null if the property is not an array or doesn't exist.

41. get

Declaration

public function get(
    string $propertyName
) : mixed|null
{
}

Description

Get the value of a property.

This method retrieves the value of the specified property. If the property does not exist, it returns null.

Parameters

$propertyName

The name of the property to retrieve.

Return

mixed|null

The value of the property, or null if the property is not set.

42. hasValue

Declaration

public function hasValue(
    string $propertyName
) : bool
{
}

Description

Check if a property has a value set.

This method checks if the specified property is set (exists and has a value). It returns true if the property exists and has a value, and false otherwise.

Parameters

$propertyName

The name of the property to check.

Return

bool

True if the property is set, false otherwise.

43. getOrDefault

Declaration

public function getOrDefault(
    string $propertyName,
    mixed|null $defaultValue = null
) : mixed|null
{
}

Description

Get the value of a property or a default value if the property is not set.

This method retrieves the value of the specified property. If the property is not set, the provided default value is returned.

Parameters

$propertyName

The name of the property to retrieve.

$defaultValue

The default value to return if the property is not set.

Return

mixed|null

The value of the property, or the default value if the property is not set.

44. __set

Declaration

public function __set(
    string $propertyName,
    mixed $propertyValue
)
{
}

Description

Set property value (magic setter).

Parameters

$propertyName

Property name

$propertyValue

Property value

45. __get

Declaration

public function __get(
    string $propertyName
) : mixed|null
{
}

Description

Magic method to get the value of a property.

This method is automatically called when an undefined or inaccessible property is accessed. It checks if the property has been set (including null values) using the __isset method and retrieves its value via the get method if it exists.

Parameters

$propertyName

The name of the property to retrieve.

Return

mixed|null

The value of the property if it is set, or null if the property is not set or accessible.

46. __isset

Declaration

public function __isset(
    string $propertyName
) : bool
{
}

Description

Magic method to check if a property is set (including null).

This method is automatically called when checking if an undefined or inaccessible property is set using isset(). It checks if the property exists and is set (even if its value is null).

Parameters

$propertyName

The name of the property to check.

Return

bool

True if the property is set (including null), false otherwise.

47. __unset

Declaration

public function __unset(
    string $propertyName
) : void
{
}

Description

Magic method to unset a property.

This method is automatically called when a property is unset using unset(). It unsets the specified property from the object.

Parameters

$propertyName

The name of the property to unset.

Return

void
48. copyValueFrom

Declaration

public function copyValueFrom(
    self|mixed $source,
    array|null $filter = null,
    bool $includeNull = false
) : self
{
}

Description

Copy values from another object to the current instance.

This method copies property values from the provided source object to the current instance. Optionally, a filter can be applied to specify which properties to copy, and whether null values should be included.

Parameters

$source

The source object or data from which values will be copied. If a non-object is provided, this may result in unexpected behavior.

$filter

An optional array of property names to filter which properties are copied. If null, all properties are copied.

$includeNull

Flag indicating whether to include properties with null values. If false, properties with null values will be excluded from the copy.

Return

self

Returns the current instance for method chaining after copying the values.

49. removeValue

Declaration

private function removeValue(
    string $propertyName,
    bool $skipModifyNullProperties = false
) : self
{
}

Description

Remove property value and set it to null.

Parameters

$propertyName

Property name

$skipModifyNullProperties

Skip modifying null properties

Return

self

Returns the current instance for method chaining.

50. tableInfo

Declaration

public function tableInfo() : PicoTableInfo
{
}

Description

Retrieve table information for the current instance.

This method retrieves the table information (e.g., schema, columns) associated with the current object. It lazily loads the table information, meaning it will be fetched only once and cached for future calls to improve performance.

Return

PicoTableInfo

Returns an instance of the PicoTableInfo class containing the table schema and other related metadata.

51. defaultValue

Declaration

public function defaultValue(
    bool $snakeCase = false
) : stdClass
{
}

Description

Get default values for properties

Parameters

$snakeCase

Flag indicating whether to convert property names to snake case

Return

stdClass

An object containing default values

52. value

Declaration

public function value(
    bool $snakeCase = false
) : stdClass
{
}

Description

Get the object values

Parameters

$snakeCase

Flag indicating whether to convert property names to snake case

Return

stdClass

An object containing the values of the properties

53. valueObject

Declaration

public function valueObject(
    boolean|null $snakeCase = null
) : stdClass
{
}

Description

Get the object value as a specified format

Parameters

$snakeCase

Flag indicating whether to convert property names to snake case; if null, default behavior is used

Return

stdClass

An object representing the value of the instance

54. valueArray

Declaration

public function valueArray(
    bool $snakeCase = false
) : array
{
}

Description

Get the object value as an associative array

Parameters

$snakeCase

Flag indicating whether to convert property names to snake case

Return

array

An associative array representing the object values

55. valueArrayUpperCamel

Declaration

public function valueArrayUpperCamel() : array
{
}

Description

Get the object value as an associative array with the first letter of each key in upper camel case

Return

array

An associative array with keys in upper camel case

56. _snakeJson

Declaration

protected function _snakeJson() : bool
{
}

Description

Check if the JSON naming strategy is snake case

Return

bool

True if the naming strategy is snake case; otherwise, false

57. _snakeYaml

Declaration

protected function _snakeYaml() : bool
{
}

Description

Check if the YAML naming strategy is snake case

Return

bool

True if the naming strategy is snake case; otherwise, false

58. _upperCamel

Declaration

protected function _upperCamel() : bool
{
}

Description

Check if the JSON naming strategy is upper camel case

Return

bool

True if the naming strategy is upper camel case; otherwise, false

59. _camel

Declaration

protected function _camel() : bool
{
}

Description

Check if the JSON naming strategy is camel case

Return

bool

True if the naming strategy is camel case; otherwise, false

60. _pretty

Declaration

protected function _pretty() : bool
{
}

Description

Check if the JSON output should be prettified

Return

bool

True if JSON output is set to be prettified; otherwise, false

61. _isArray

Declaration

private function _isArray(
    mixed $params
) : bool
{
}

Description

Checks if the provided parameter is an array.

This function verifies if the given parameter is set and is of type array. It is a helper method used to validate the type of data before performing any operations on it that require an array.

Parameters

$params

The parameter to check.

Return

bool

Returns true if the parameter is set and is an array, otherwise returns false.

62. _isNotNullAndNotEmpty

Declaration

private function _isNotNullAndNotEmpty(
    mixed $value
) : bool
{
}

Description

Check if a value is not null and not empty

Parameters

$value

The value to check

Return

bool

True if the value is not null and not empty; otherwise, false

63. propertyList

Declaration

protected function propertyList(
    bool $reflectSelf = false,
    bool $asArrayProps = false
) : array
{
}

Description

Get a list of properties

Parameters

$reflectSelf

Flag indicating whether to reflect properties of the current class

$asArrayProps

Flag indicating whether to return properties as an array

Return

array

An array of property names or ReflectionProperty objects

64. listAll

Declaration

public function listAll(
    PicoSpecification|null $specification = null,
    PicoPageable|string|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    bool $passive = false,
    array|null $subqueryMap = null
) : PicoPageData
{
}

Description

List all records

Parameters

$specification

The specification for filtering

$pageable

The pagination information

$sortable

The sorting criteria

$passive

Flag indicating whether the object is passive

$subqueryMap

An optional map of subqueries

Return

PicoPageData

The paginated data

Throws

NoRecordFoundException

if no records are found

NoDatabaseConnectionException

if no database connection is established

65. countData

Declaration

private function countData(
    PicoDatabasePersistence $persist,
    PicoSpecification|null $specification,
    PicoPageable|string|null $pageable,
    PicoSortable|string|null $sortable,
    int $findOption = 0,
    array|null $result = null
) : int
{
}

Description

Count the data based on specifications

Parameters

$persist

The persistence object

$specification

The specification for filtering

$pageable

The pagination information

$sortable

The sorting criteria

$findOption

The find option

$result

The result set

Return

int

The count of matching records

66. findOne

Declaration

public function findOne(
    PicoSpecification|null $specification = null,
    PicoSortable|string|null $sortable = null,
    array|null $subqueryMap = null
) : self
{
}

Description

Find one record based on specifications

Parameters

$specification

The specification for filtering

$sortable

The sorting criteria

$subqueryMap

An optional map of subqueries

Return

self

The found instance.

Throws

NoRecordFoundException

if no record is found

NoDatabaseConnectionException

if no database connection is established

67. findAll

Declaration

public function findAll(
    PicoSpecification|null $specification = null,
    PicoPageable|string|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    bool $passive = false,
    array|null $subqueryMap = null,
    int $findOption = 0
) : PicoPageData
{
}

Description

Find all records based on specifications

Parameters

$specification

The specification for filtering

$pageable

The pagination information

$sortable

The sorting criteria

$passive

Flag indicating whether the object is passive

$subqueryMap

An optional map of subqueries

$findOption

The find option

Return

PicoPageData

The paginated data

Throws

NoRecordFoundException

if no records are found

NoDatabaseConnectionException

if no database connection is established

68. findAllAsc

Declaration

public function findAllAsc() : PicoPageData
{
}

Description

Find all records without filters, sorted by primary key in ascending order

Return

PicoPageData

The paginated data

69. findAllDesc

Declaration

public function findAllDesc() : PicoPageData
{
}

Description

Find all records without filters, sorted by primary key in descending order

Return

PicoPageData

The paginated data

70. findSpecific

Declaration

public function findSpecific(
    string $selected,
    PicoSpecification|null $specification = null,
    PicoPageable|string|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    bool $passive = false,
    array|null $subqueryMap = null,
    int $findOption = 0
) : PicoPageData
{
}

Description

Find specific records

Parameters

$selected

The selected field(s)

$specification

The specification for filtering

$pageable

The pagination information

$sortable

The sorting criteria

$passive

Flag indicating whether the object is passive

$subqueryMap

An optional map of subqueries

$findOption

The find option

Return

PicoPageData

The paginated data

Throws

NoRecordFoundException

if no records are found

NoDatabaseConnectionException

if no database connection is established

71. countDataCustom

Declaration

private function countDataCustom(
    PicoDatabasePersistence $persist,
    PicoSpecification|null $specification,
    PicoPageable|string|null $pageable,
    PicoSortable|string|null $sortable,
    int $findOption,
    mixed $result
) : int
{
}

Description

Counts the total number of records for a given query, with special handling for SQLite.

Parameters

$persist

The persistence object to interact with the database.

$specification

The specification used to filter the results.

$pageable

Pagination information.

$sortable

Sorting information.

$findOption

The find option flag indicating how the query should be executed.

$result

The result set to count.

Return

int

The total number of matching records.

72. countDataCustomWithPagable

Declaration

private function countDataCustomWithPagable(
    PicoDatabasePersistence $persist,
    PicoSpecification|null $specification,
    PicoPageable|string|null $pageable,
    PicoSortable|string|null $sortable,
    int $findOption,
    mixed $result
) : int
{
}

Description

Counts the total number of records for a given query with pagination, with special handling for SQLite.

Parameters

$persist

The persistence object to interact with the database.

$specification

The specification used to filter the results.

$pageable

Pagination information.

$sortable

Sorting information.

$findOption

The find option flag indicating how the query should be executed.

$result

The result set to count.

Return

int

The total number of matching records considering pagination.

73. countAll

Declaration

public function countAll(
    PicoSpecification|null $specification = null,
    PicoPageable|null $pageable = null,
    PicoSortable|null $sortable = null
) : int|false
{
}

Description

Count all records based on specifications

Parameters

$specification

The specification for filtering

$pageable

The pagination information

$sortable

The sorting criteria

Return

int|false

The count of records or false on error

Throws

NoRecordFoundException

if no records are found

NoDatabaseConnectionException

if no database connection is established

74. findAllQuery

Declaration

public function findAllQuery(
    PicoSpecification|null $specification = null,
    PicoPageable|string|null $pageable = null,
    PicoSortable|string|null $sortable = null
) : PicoDatabaseQueryBuilder
{
}

Description

Build a query to find all records

Parameters

$specification

The specification for filtering

$pageable

The pagination information

$sortable

The sorting criteria

Return

PicoDatabaseQueryBuilder

The query builder

Throws

NoRecordFoundException

if no record is found

NoDatabaseConnectionException

if no database connection is established

75. find

Declaration

public function find(
    mixed $params
) : self
{
}

Description

Find one record by primary key value

Parameters

$params

The parameters for the search

Return

self

The found instance.

Throws

NoRecordFoundException

if no record is found

NoDatabaseConnectionException

if no database connection is established

76. findIfExists

Declaration

public function findIfExists(
    array $params
) : self
{
}

Description

Find one record if it exists by primary key value

Parameters

$params

The parameters for the search

Return

self

The found instance. or the current instance if not found

77. findBy

Declaration

private function findBy(
    string $method,
    mixed $params,
    PicoSpecification|null $specification,
    PicoPageable|string|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    bool $passive = false,
    array|null $subqueryMap = null
) : PicoPageData
{
}

Description

Find records by specified parameters

Parameters

$method

The method to find by

$params

The parameters for the search

$specification

The specification for filtering

$pageable

The pagination information

$sortable

The sorting criteria

$passive

Flag indicating whether the object is passive

$subqueryMap

An optional map of subqueries

Return

PicoPageData

The paginated data

Throws

NoRecordFoundException

if no records are found

NoDatabaseConnectionException

if no database connection is established

78. countBy

Declaration

private function countBy(
    string $method,
    mixed $params
) : int
{
}

Description

Count data from the database.

Parameters

$method

The method used for finding.

$params

The parameters to use for the count.

Return

int

The count of matching records.

Throws

NoDatabaseConnectionException

If there is no database connection.

79. deleteBy

Declaration

private function deleteBy(
    string $method,
    mixed $params
) : int
{
}

Description

Delete records based on parameters.

Parameters

$method

The method used for finding.

$params

The parameters to use for the deletion.

Return

int

The number of deleted records.

Throws

NoDatabaseConnectionException

If there is no database connection.

80. findOneWithPrimaryKeyValue

Declaration

public function findOneWithPrimaryKeyValue(
    mixed $primaryKeyVal,
    array|null $subqueryMap = null
) : self
{
}

Description

Find one record using the primary key value.

Parameters

$primaryKeyVal

The primary key value.

$subqueryMap

Optional subquery map for additional queries.

Return

self

The found instance.

Throws

NoRecordFoundException

If no record is found.

NoDatabaseConnectionException

If there is no database connection.

81. findOneBy

Declaration

private function findOneBy(
    string $method,
    mixed $params,
    PicoSortable|string|null $sortable = null
) : object
{
}

Description

Find one record based on specified parameters.

Parameters

$method

The method used for finding.

$params

The parameters to use for the search.

$sortable

Optional sorting criteria.

Return

object

The found instance.

Throws

NoRecordFoundException

If no record is found.

NoDatabaseConnectionException

If there is no database connection.

82. findOneIfExistsBy

Declaration

private function findOneIfExistsBy(
    string $method,
    mixed $params,
    PicoSortable|string|null $sortable = null
) : object
{
}

Description

Find one record if it exists based on parameters.

Parameters

$method

The method used for finding.

$params

The parameters to use for the search.

$sortable

Optional sorting criteria.

Return

object

The found instance or the current instance if not found.

Throws

NoDatabaseConnectionException

If there is no database connection.

83. deleteOneBy

Declaration

private function deleteOneBy(
    string $method,
    mixed $params
) : bool
{
}

Description

Delete one record based on specified parameters.

Parameters

$method

The method used for finding.

$params

The parameters to use for the deletion.

Return

bool

True on success; otherwise, false.

Throws

NoDatabaseConnectionException

If there is no database connection.

84. existsBy

Declaration

private function existsBy(
    string $method,
    mixed $params
) : bool
{
}

Description

Check if a record exists based on specified parameters.

Parameters

$method

The method used for finding.

$params

The parameters to use for the search.

Return

bool

True if the record exists; otherwise, false.

Throws

NoDatabaseConnectionException

If there is no database connection.

85. booleanToTextBy

Declaration

private function booleanToTextBy(
    string $propertyName,
    string[] $params
) : string
{
}

Description

Convert a boolean value to text based on the specified property name.

Parameters

$propertyName

The property name to check.

$params

The text representations for true and false.

Return

string

The corresponding text representation.

86. toArrayObject

Declaration

private function toArrayObject(
    array $result,
    bool $passive = false
) : array
{
}

Description

Convert the result to an array of objects.

Parameters

$result

The result set to convert.

$passive

Flag indicating whether the objects are passive.

Return

array

An array of objects.

87. size

Declaration

public function size() : int
{
}

Description

Get the number of properties of the object.

Return

int

The number of properties.

88. __call

Declaration

public function __call(
    string $method,
    mixed $params
) : mixed|null
{
}

Description

Magic method called when a user calls any undefined method. The __call method checks the prefix of the called method and invokes the appropriate method according to its name and parameters.

Method Descriptions:

  • hasValue: Checks if the property has a value.

    • Example: $object->hasValuePropertyName();
  • isset: Checks if the property is set.

    • Example: $object->issetPropertyName();
  • is: Retrieves the property value as a boolean.

    • Example: $isActive = $object->isActive();
  • equals: Checks if the property value equals the given value.

    • Example: $isEqual = $object->equalsPropertyName($value);
  • get: Retrieves the property value.

    • Example: $value = $object->getPropertyName();
  • set: Sets the property value.

    • Example: $object->setPropertyName($value);
  • unset: Unsets the property value.

    • Example: $object->unsetPropertyName();
  • push: Adds array elements to a property at the end.

    • Example: $object->pushPropertyName($newElement);
  • append: Appends array elements to a property at the end.

    • Example: $object->appendPropertyName($newElement);
  • unshift: Adds array elements to a property at the beginning.

    • Example: $object->unshiftPropertyName($newElement);
  • prepend: Prepends array elements to a property at the beginning.

    • Example: $object->prependPropertyName($newElement);
  • pop: Removes the last element from the property.

    • Example: $removedElement = $object->popPropertyName();
  • shift: Removes the first element from the property.

    • Example: $removedElement = $object->shiftPropertyName();
  • findOneBy: Searches for data in the database and returns one record.

    • Example: $record = $object->findOneByPropertyName($value);
    • Requires a database connection.
  • findOneIfExistsBy: Searches for data in the database by any column values and returns one record.

    • Example: $record = $object->findOneIfExistsByPropertyName($value, $sortable);
    • Requires a database connection.
  • deleteOneBy: Deletes data from the database by any column values and returns one record.

    • Example: $deletedRecord = $object->deleteOneByPropertyName($value, $sortable);
    • Requires a database connection.
  • findFirstBy: Searches for data in the database by any column values and returns the first record.

    • Example: $firstRecord = $object->findFirstByColumnName($value);
    • Requires a database connection.
  • findFirstIfExistsBy: Similar to findFirstBy, but returns the first record if it exists.

    • Example: $firstRecord = $object->findFirstIfExistsByPropertyName($value, $sortable);
    • Requires a database connection.
  • findLastBy: Searches for data in the database by any column values and returns the last record.

    • Example: $lastRecord = $object->findLastByColumnName($value);
    • Requires a database connection.
  • findLastIfExistsBy: Similar to findLastBy, but returns the last record if it exists.

    • Example: $lastRecord = $object->findLastIfExistsByPropertyName($value, $sortable);
    • Requires a database connection.
  • findBy: Searches for multiple records in the database by any column values.

    • Example: $records = $object->findByColumnName($value);
    • Requires a database connection.
  • countBy: Counts data from the database.

    • Example: $count = $object->countByColumnName();
  • existsBy: Checks for data in the database.

    • Example: $exists = $object->existsByColumn($column);
    • Requires a database connection.
  • deleteBy: Deletes data from the database without reading it first.

    • Example: $object->deleteByPropertyName($value);
    • Requires a database connection.
  • booleanToTextBy: Converts a boolean value to "yes/no" or "true/false" based on given parameters.

    • Example: $result = $object->booleanToTextByActive("Yes", "No");
    • If $obj->active is true, $result will be "Yes"; otherwise, it will be "No".
  • startsWith: Checks if the value starts with a given string.

    • Example: $startsWith = $object->startsWithPropertyName("prefix");
  • endsWith: Checks if the value ends with a given string.

    • Example: $endsWith = $object->endsWithPropertyName("suffix");
  • label: Retrieves the label associated with the given property.

    • If the label is not set, it attempts to fetch it from annotations.
    • Example: $label = $object->labelPropertyName();
  • option: Returns the first parameter if the property is set to true or equals 1; otherwise returns the second parameter.

    • Example: $option = $object->optionPropertyName("Yes", "No");
  • notNull: Checks if the specified property is set (not null).

    • Example: $isNotNull = $object->notNullPropertyName();
  • notEmpty: Checks if the specified property is set and not empty.

    • Example: $isNotEmpty = $object->notEmptyPropertyName();
  • notZero: Checks if the specified property is set and not equal to zero.

    • Example: $isNotZero = $object->notZeroPropertyName();
  • notEquals: Checks if the specified property is set and does not equal the given value.

    • Example: $isNotEqual = $object->notEqualsPropertyName($value);

Parameters

$method

Method name

$params

Parameters for the method

Return

mixed|null

The result of the called method, or null if not applicable

89. __toString

Declaration

public function __toString() : string
{
}

Description

Magic method to convert the object to a string.

Return

string

A JSON representation of the object.

90. stringifyObject

Declaration

private function stringifyObject(
    self $value,
    bool $snake
) : mixed
{
}

Description

Recursively stringify an object or array of objects.

Parameters

$value

The object to stringify.

$snake

Flag to indicate whether to convert property names to snake_case.

Return

mixed

The stringified object or array.

91. dumpYaml

Declaration

public function dumpYaml(
    int|null $inline = null,
    int $indent = 4,
    int $flags = 0
) : string
{
}

Description

Dumps a PHP value to a YAML string.

The dump method, when supplied with an array, converts it into a friendly YAML format.

Parameters

$inline

The level at which to switch to inline YAML. If NULL, the maximum depth will be used.

$indent

The number of spaces to use for indentation of nested nodes.

$flags

A bit field of DUMP_* constants to customize the dumped YAML string.

Return

string

A YAML string representing the original PHP value.

MagicObject\SecretObject

Declaration

class SecretObject extends stdClass { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

SecretObject class

This class provides mechanisms to manage properties that require encryption and decryption during their lifecycle. It uses annotations to specify which properties should be encrypted or decrypted when they are set or retrieved. These annotations help identify when to apply encryption or decryption, either before saving (SET) or before fetching (GET).

The class supports flexibility in data initialization, allowing data to be passed as an array, an object, or even left empty. Additionally, a secure callback function can be provided to handle key generation for encryption and decryption operations.

Key features:

  • Encryption and decryption of object properties based on annotations.
  • Support for customizing property naming strategies.
  • Option to provide a secure function for key generation.

Constants

const JSON = "JSON";
const YAML = "Yaml";
const PROPERTY_NAMING_STRATEGY = "property-naming-strategy";
const PROPERTY_NAMING_STRATEGY_CAMEL = "propertyNamingStrategy";
const KEY_NAME = "name";
const KEY_VALUE = "value";
const KEY_PROPERTY_TYPE = "propertyType";
const KEY_DEFAULT_VALUE = "defaultValue";
const ANNOTATION_ENCRYPT_IN = "EncryptIn";
const ANNOTATION_DECRYPT_IN = "DecryptIn";
const ANNOTATION_ENCRYPT_OUT = "EncryptOut";
const ANNOTATION_DECRYPT_OUT = "DecryptOut";
const SNAKE_CASE = "SNAKE_CASE";
const UPPER_CAMEL_CASE = "UPPER_CAMEL_CASE";

Properties

1. _encryptInProperties

Declaration

private string[] $_encryptInProperties = array();

Description

List of properties to be encrypted when calling SET.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _classParams

Declaration

protected array $_classParams = array();

Description

Class parameters.

The property name starts with an underscore to prevent child classes from overriding its value.

3. _nullProperties

Declaration

protected array $_nullProperties = array();

Description

NULL properties.

The property name starts with an underscore to prevent child classes from overriding its value.

4. _decryptOutProperties

Declaration

private string[] $_decryptOutProperties = array();

Description

List of properties to be decrypted when calling GET.

The property name starts with an underscore to prevent child classes from overriding its value.

5. _encryptOutProperties

Declaration

private string[] $_encryptOutProperties = array();

Description

List of properties to be encrypted when calling GET.

The property name starts with an underscore to prevent child classes from overriding its value.

6. _decryptInProperties

Declaration

private string[] $_decryptInProperties = array();

Description

List of properties to be decrypted when calling SET.

The property name starts with an underscore to prevent child classes from overriding its value.

7. _readonly

Declaration

private boolean $_readonly = false;

Description

Indicates if the object is read-only.

The property name starts with an underscore to prevent child classes from overriding its value.

8. _secureFunction

Declaration

private callable $_secureFunction;

Description

Secure function to get encryption key.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

1. __construct

Declaration

public function __construct(
    self|array|object|null $data = null,
    callable|null $secureCallback = null
)
{
}

Description

Constructor for initializing the object with data.

This constructor accepts initial data in various formats (array or object) and allows the optional specification of a callback function for secure key generation. The data is processed and loaded into the object upon instantiation.

Parameters

$data

The initial data for the object. Can be an

$secureCallback

An optional callback function for generating

2. _objectInfo

Declaration

private function _objectInfo() : void
{
}

Description

Analyzes the class's parameters and properties to determine which should be encrypted or decrypted based on annotations.

This method uses reflection to retrieve the class's parameters and properties. It then parses annotations associated with these members to identify which properties should undergo encryption or decryption during specific stages (before storage or before retrieval). The appropriate lists of properties are populated accordingly.

Return

void

Throws

InvalidAnnotationException

If the annotations are invalid or cannot be parsed.

3. secureKey

Declaration

private function secureKey() : string
{
}

Description

Generates a secure key for encryption and decryption.

This method checks for a user-defined secure key generation function. If a valid function is provided, it calls that function to generate the key. Otherwise, it returns a concatenation of predefined random keys.

Return

string

The secure key for encryption/decryption.

4. __call

Declaration

public function __call(
    string $method,
    array $params
) : mixed|null
{
}

Description

Magic method called when invoking undefined methods.

This method handles dynamic method calls for property management.

Supported methods:

  • isset<PropertyName>: Checks if the property is set.

    • Example: $obj->issetFoo() returns true if property foo is set.
  • is<PropertyName>: Checks if the property is set and equals 1 (truthy).

    • Example: $obj->isFoo() returns true if property foo is set and is equal to 1.
  • get<PropertyName>: Retrieves the value of the property.

    • Example: $value = $obj->getFoo() gets the value of property foo.
  • set<PropertyName>: Sets the value of the property.

    • Example: $obj->setFoo($value) sets the property foo to $value.
  • unset<PropertyName>: Unsets the property.

    • Example: $obj->unsetFoo() removes the property foo.
  • push<PropertyName>: Pushes a value onto an array property.

    • Example: $obj->pushFoo($value) adds $value to the array property foo.
  • pop<PropertyName>: Pops a value from an array property.

    • Example: $value = $obj->popFoo() removes and returns the last value from the array property foo.

Parameters

$method

Method name.

$params

Parameters for the method.

Return

mixed|null

The result of the method call or null if not applicable.

5. _set

Declaration

private function _set(
    string $var,
    mixed $value
) : self
{
}

Description

Set a value for the specified property.

This method sets the value of a property and applies encryption or decryption if necessary based on the defined property rules.

Parameters

$var

The name of the property.

$value

The value to set.

Return

self
6. _get

Declaration

private function _get(
    string $var
) : mixed
{
}

Description

Get the value of the specified property.

This method retrieves the value of a property and applies encryption or decryption if necessary based on the defined property rules.

Parameters

$var

The name of the property.

Return

mixed

The value of the property.

7. _getValue

Declaration

private function _getValue(
    string $var
) : mixed
{
}

Description

Get the raw value of the specified property.

This method retrieves the raw value of a property without any encryption or decryption.

Parameters

$var

The name of the property.

Return

mixed

The raw value of the property, or null if not set.

8. typeObject

Declaration

private function typeObject(
    mixed $data
) : bool
{
}

Description

Check if the given data is an instance of MagicObject or PicoGenericObject.

Parameters

$data

The data to check.

Return

bool

True if the data is an instance, otherwise false.

9. typeStdClass

Declaration

private function typeStdClass(
    mixed $data
) : bool
{
}

Description

Check if the given data is an instance of self or stdClass.

Parameters

$data

The data to check.

Return

bool

True if the data is an instance, otherwise false.

10. encryptValue

Declaration

public function encryptValue(
    MagicObject|PicoGenericObject|self|array|stdClass|string|number $data,
    string|null $hexKey = null
) : mixed
{
}

Description

Encrypt data recursively.

This method encrypts the provided data, which can be an object, array, or scalar value. It handles nested structures by encrypting each value individually.

Parameters

$data

The data to encrypt.

$hexKey

The encryption key in hexadecimal format. If null, a secure key will be generated.

Return

mixed

The encrypted data.

11. encryptString

Declaration

public function encryptString(
    string $plaintext,
    string|null $hexKey = null
) : string
{
}

Description

Encrypt a string.

This method encrypts a plain text string using a specified or generated secure key.

Parameters

$plaintext

The plain text to be encrypted.

$hexKey

The key in hexadecimal format. If null, a secure key will be generated.

Return

string

The encrypted string in base64 format.

12. decryptValue

Declaration

public function decryptValue(
    MagicObject|PicoGenericObject|self|array|stdClass|string $data,
    string|null $hexKey = null
) : string|null
{
}

Description

Decrypt data recursively.

This method decrypts the provided ciphertext, which can be an object, array, or scalar value. It handles nested structures by decrypting each value individually.

Parameters

$data

The ciphertext to decrypt.

$hexKey

The key in hexadecimal format. If null, a secure key will be generated.

Return

string|null

The decrypted string or null if decryption fails.

13. decryptString

Declaration

public function decryptString(
    string $ciphertext,
    string|null $hexKey = null
) : string|null
{
}

Description

Decrypt a string.

This method decrypts a given ciphertext string using a specified or generated secure key.

Parameters

$ciphertext

The encrypted data to be decrypted.

$hexKey

The key in hexadecimal format. If null, a secure key will be generated.

Return

string|null

The decrypted string or null if decryption fails.

14. needInputEncryption

Declaration

private function needInputEncryption(
    string $var
) : bool
{
}

Description

Check if a value requires encryption before being stored.

Parameters

$var

The variable name.

Return

bool

True if the value needs to be encrypted, otherwise false.

15. needOutputDecryption

Declaration

private function needOutputDecryption(
    string $var
) : bool
{
}

Description

Check if a value requires decryption after being read.

Parameters

$var

The variable name.

Return

bool

True if the value needs to be decrypted, otherwise false.

16. needOutputEncryption

Declaration

private function needOutputEncryption(
    string $var
) : bool
{
}

Description

Check if a value requires encryption after being read.

Parameters

$var

The variable name.

Return

bool

True if the value needs to be encrypted, otherwise false.

17. needInputDecryption

Declaration

private function needInputDecryption(
    string $var
) : bool
{
}

Description

Check if a value requires decryption before being stored.

Parameters

$var

The variable name.

Return

bool

True if the value needs to be decrypted, otherwise false.

18. loadData

Declaration

public function loadData(
    mixed $data
) : self
{
}

Description

Load data into the object.

This method populates the object's properties from the provided data, which can be an object, array, or scalar value.

Parameters

$data

The data to load.

Return

self

Returns the current instance for method chaining.

19. loadIniString

Declaration

public function loadIniString(
    string $rawData,
    bool $systemEnv = false
) : self
{
}

Description

Load data from an INI string.

This method parses an INI formatted string and loads the data into the object.

Parameters

$rawData

The raw INI data as a string.

$systemEnv

Flag to indicate whether to use environment variable replacement.

Return

self

Returns the current instance for method chaining.

20. loadIniFile

Declaration

public function loadIniFile(
    string $path,
    bool $systemEnv = false
) : self
{
}

Description

Load data from an INI file.

This method reads an INI file and loads the data into the object.

Parameters

$path

The path to the INI file.

$systemEnv

Flag to indicate whether to use environment variable replacement.

Return

self

Returns the current instance for method chaining.

21. loadYamlString

Declaration

public function loadYamlString(
    string $rawData,
    bool $systemEnv = false,
    bool $asObject = false,
    bool $recursive = false
) : self
{
}

Description

Load data from a YAML string.

This method parses a YAML formatted string and loads the data into the object.

Parameters

$rawData

The YAML data as a string.

$systemEnv

Flag to indicate whether to replace environment variables.

$asObject

Flag to indicate whether to return results as an object.

$recursive

Flag to indicate whether to convert nested objects to MagicObject.

Return

self

Returns the current instance for method chaining.

22. loadYamlFile

Declaration

public function loadYamlFile(
    string $path,
    bool $systemEnv = false,
    bool $asObject = false,
    bool $recursive = false
) : self
{
}

Description

Load data from a YAML file.

This method reads a YAML file and loads the data into the object.

Parameters

$path

The path to the YAML file.

$systemEnv

Flag to indicate whether to replace environment variables.

$asObject

Flag to indicate whether to return results as an object.

$recursive

Flag to indicate whether to convert nested objects to MagicObject.

Return

self

Returns the current instance for method chaining.

23. loadJsonString

Declaration

public function loadJsonString(
    string $rawData,
    bool $systemEnv = false,
    bool $recursive = false
) : self
{
}

Description

Load data from a JSON string.

This method parses a JSON formatted string and loads the data into the object.

Parameters

$rawData

The JSON data as a string.

$systemEnv

Flag to indicate whether to replace environment variables.

$recursive

Flag to create recursive object.

Return

self

Returns the current instance for method chaining.

24. loadJsonFile

Declaration

public function loadJsonFile(
    string $path,
    bool $systemEnv = false,
    bool $recursive = false
) : self
{
}

Description

Load data from a JSON file.

This method reads a JSON file and loads the data into the object.

Parameters

$path

The path to the JSON file.

$systemEnv

Flag to indicate whether to replace environment variables.

$recursive

Flag to create recursive object.

Return

self

Returns the current instance for method chaining.

25. readOnly

Declaration

protected function readOnly(
    bool $readonly
) : self
{
}

Description

Set the object to read-only mode.

When in read-only mode, setters will not change the value of the object's properties, but the loadData method will still work.

Parameters

$readonly

Flag to set the object to read-only.

Return

self

Returns the current instance for method chaining.

26. set

Declaration

public function set(
    string $propertyName,
    mixed|null $propertyValue
) : self
{
}

Description

Set a property value.

Parameters

$propertyName

The name of the property to set.

$propertyValue

The value to set for the property.

Return

self

Returns the current instance for method chaining.

27. push

Declaration

public function push(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Add an element to a property array.

Parameters

$propertyName

The name of the property.

$propertyValue

The value to add.

Return

self

Returns the current instance for method chaining.

28. pop

Declaration

public function pop(
    string $propertyName
) : mixed|null
{
}

Description

Remove the last element from a property array.

Parameters

$propertyName

The name of the property.

Return

mixed|null

The removed value or null if the property is not an array.

29. get

Declaration

public function get(
    string $propertyName
) : mixed|null
{
}

Description

Get a property value.

Parameters

$propertyName

The name of the property.

Return

mixed|null

The value of the property or null if not set.

30. getOrDefault

Declaration

public function getOrDefault(
    string $propertyName,
    mixed|null $defaultValue = null
) : mixed
{
}

Description

Get a property value or return a default value if not set.

Parameters

$propertyName

The name of the property.

$defaultValue

The default value to return if the property is not set.

Return

mixed

The property value or the default value.

31. copyValueFrom

Declaration

public function copyValueFrom(
    self|mixed $source,
    array|null $filter = null,
    bool $includeNull = false
) : self
{
}

Description

Copies values from another object to the current object based on specified filters.

This method allows selective copying of property values from a source object to the current object. You can specify which properties to copy using a filter, and you can choose whether to include properties with null values.

Parameters

$source

The source object from which to copy values.

$filter

An optional array of property names to filter which values

$includeNull

A flag indicating whether to include properties with null

Return

self

Returns the current instance for method chaining.

32. value

Declaration

public function value(
    bool $snakeCase = false
) : stdClass
{
}

Description

Get object value.

This method retrieves the values of the object's properties, optionally converting the property names to snake case.

Parameters

$snakeCase

Flag to convert property names to snake case.

Return

stdClass

An object containing the values of the properties.

33. valueObject

Declaration

public function valueObject(
    bool $snakeCase = false
) : stdClass
{
}

Description

Get object value as an object.

This method is an alias for the value() method, allowing for retrieval of object values, optionally in snake case.

Parameters

$snakeCase

Flag to convert property names to snake case.

Return

stdClass

An object containing the values of the properties.

34. valueArray

Declaration

public function valueArray(
    bool $snakeCase = false
) : array
{
}

Description

Get object value as an associative array.

This method retrieves the object values and converts them to an associative array, optionally converting property names to snake case.

Parameters

$snakeCase

Flag to convert property names to snake case.

Return

array

An associative array containing the values of the properties.

35. valueArrayUpperCamel

Declaration

public function valueArrayUpperCamel() : array
{
}

Description

Get object value as an associative array with upper camel case keys.

This method retrieves the object values and converts them to an associative array, with keys formatted in upper camel case.

Return

array

An associative array containing the values of the properties with upper camel case keys.

36. _snakeJson

Declaration

protected function _snakeJson() : bool
{
}

Description

Check if JSON naming strategy is snake case.

Return

bool

True if the naming strategy is snake case, otherwise false.

37. _snakeYaml

Declaration

protected function _snakeYaml() : bool
{
}

Description

Check if YAML naming strategy is snake case.

Return

bool

True if the naming strategy is snake case, otherwise false.

38. isUpperCamel

Declaration

protected function isUpperCamel() : bool
{
}

Description

Check if JSON naming strategy is upper camel case.

Return

bool

True if the naming strategy is upper camel case, otherwise false.

39. _pretty

Declaration

protected function _pretty() : bool
{
}

Description

Check if the JSON output should be prettified

Return

bool

True if JSON output is set to be prettified; otherwise, false

40. _camel

Declaration

protected function _camel() : bool
{
}

Description

Check if JSON naming strategy is camel case.

Return

bool

True if the naming strategy is camel case, otherwise false.

41. propertyList

Declaration

protected function propertyList(
    bool $reflectSelf = false,
    bool $asArrayProps = false
) : array
{
}

Description

Get the list of properties of the class.

This method returns an array of properties defined in the class, optionally reflecting the self class or converting the properties to an array.

Parameters

$reflectSelf

Flag to include properties defined in the current class.

$asArrayProps

Flag to return properties as an array.

Return

array

An array of ReflectionProperty objects or property names.

42. modifyNullProperties

Declaration

private function modifyNullProperties(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Modify null properties.

This method keeps track of properties that have been set to null, allowing for tracking changes to properties.

Parameters

$propertyName

The name of the property.

$propertyValue

The value of the property.

Return

self

Returns the current instance for method chaining.

43. encryptedValue

Declaration

public function encryptedValue() : array
{
}

Description

Get the encrypted value of the object.

This method returns an array representation of the object's encrypted values.

Return

array

An array containing the encrypted values.

44. encryptValueRecursive

Declaration

private function encryptValueRecursive(
    array $array
) : array
{
}

Description

Encrypt values recursively.

This method encrypts each string value in the provided array. Nested arrays are also processed.

Parameters

$array

The array of values to be encrypted.

Return

array

The array with encrypted values.

45. dumpYaml

Declaration

public function dumpYaml(
    int|null $inline = null,
    int $indent = 4,
    int $flags = 0
) : string
{
}

Description

Dumps a PHP value to a YAML string.

This method attempts to convert an array into a friendly YAML format.

Parameters

$inline

The level where to switch to inline YAML. If set to NULL,

$indent

The number of spaces to use for indentation of nested nodes.

$flags

A bit field of DUMP_* constants to customize the dumped YAML string.

Return

string

A YAML string representing the original PHP value.

46. __toString

Declaration

public function __toString() : string
{
}

Description

Magic method to convert the object to a string.

This method returns a JSON representation of the object.

Return

string

A JSON representation of the object.

MagicObject\SetterGetter

Declaration

class SetterGetter extends stdClass { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class SetterGetter

A dynamic object that provides getter and setter methods for properties, allowing flexible management of property values and array-like behavior. Supports annotations for property configuration and JSON serialization.

Constants

const JSON = "JSON";

Properties

1. _classParams

Declaration

private array $_classParams = array();

Description

Class parameter storage.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

1. __construct

Declaration

public function __construct(
    self|array|stdClass|object|null $data = null
)
{
}

Description

Constructor.

Initializes the object with data and parses class annotations for property configuration.

Parameters

$data

Initial data for the object.

2. loadData

Declaration

public function loadData(
    mixed $data
) : self
{
}

Description

Load data into the object.

Maps the given data to the object's properties, automatically camelizing keys.

Parameters

$data

Data to load, which can be another SetterGetter instance,

Return

self

Returns the current instance for method chaining.

3. set

Declaration

public function set(
    string $propertyName,
    mixed|null $propertyValue
) : self
{
}

Description

Set a property value.

Parameters

$propertyName

Name of the property to set.

$propertyValue

Value to assign to the property.

Return

self

Returns the current instance for method chaining.

4. push

Declaration

public function push(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Add an element to an array property.

Initializes the property as an array if it is not already set.

Parameters

$propertyName

Name of the property to push to.

$propertyValue

Value to add to the property array.

Return

self

Returns the current instance for method chaining.

5. pop

Declaration

public function pop(
    string $propertyName
) : mixed|null
{
}

Description

Remove the last element from an array property.

Parameters

$propertyName

Name of the property to pop from.

Return

mixed|null

Returns the removed value or null if the property is not an array.

6. get

Declaration

public function get(
    string $propertyName
) : mixed|null
{
}

Description

Get a property value.

Parameters

$propertyName

Name of the property to retrieve.

Return

mixed|null

Returns the property value or null if not set.

7. __set

Declaration

public function __set(
    string $name,
    mixed $value
) : void
{
}

Description

Magic setter method.

Enables setting properties using object syntax, e.g., $instance->foo = 'bar';.

Parameters

$name

Name of the property to set.

$value

Value to assign to the property.

Return

void
8. __get

Declaration

public function __get(
    string $name
) : mixed|null
{
}

Description

Magic getter method.

Enables retrieving properties using object syntax, e.g., echo $instance->foo;.

Parameters

$name

Name of the property to retrieve.

Return

mixed|null

Returns the value of the property or null if not set.

9. __isset

Declaration

public function __isset(
    string $name
) : bool
{
}

Description

Check if a property is set.

Parameters

$name

Name of the property to check.

Return

bool

Returns true if the property is set, false otherwise.

10. __unset

Declaration

public function __unset(
    bool $snakeCase
) : stdClass
{
}

Description

Get values of the properties.

Optionally converts property names to snake_case for the returned object.

Parameters

$snakeCase

Flag to determine if property names should be converted to snake_case.

Return

stdClass

Returns an object with property values.

11. value

Declaration

public function value(
    bool $snakeCase = false
) : stdClass
{
}

Description

Get values of the properties.

Optionally converts property names to snake_case for the returned object.

Parameters

$snakeCase

Flag to determine if property names should be converted to snake_case.

Return

stdClass

Returns an object with property values.

12. propertyList

Declaration

protected function propertyList(
    bool $reflectSelf = false,
    bool $asArrayProps = false
) : array|ReflectionProperty[]
{
}

Description

Get a list of properties.

Parameters

$reflectSelf

Flag to determine if only properties of the current class should be included.

$asArrayProps

Flag to convert the properties to an array.

Return

array|ReflectionProperty[]

Returns an array of ReflectionProperty objects or property names based on $asArrayProps.

13. __call

Declaration

public function __call(
    string $method,
    array $params
) : mixed|null
{
}

Description

Magic method called when invoking undefined methods.

This method dynamically handles method calls for property management.

Supported dynamic methods:

  • isset<PropertyName>: Checks if the specified property is set.

    • Returns true if the property exists and is not null.
    • Example: $obj->issetFoo() checks if the property foo is set.
  • is<PropertyName>: Checks if the specified property is set and equals 1 (truthy).

    • Returns true if the property exists and its value is equal to 1.
    • Example: $obj->isFoo() checks if foo is set to 1.
  • get<PropertyName>: Retrieves the value of the specified property.

    • Returns the property value or null if it doesn't exist.
    • Example: $value = $obj->getFoo() gets the value of property foo.
  • set<PropertyName>: Sets the value of the specified property.

    • Accepts a single parameter which is the value to be assigned to the property.
    • Example: $obj->setFoo($value) sets the property foo to $value.
  • unset<PropertyName>: Removes the specified property from the object.

    • Example: $obj->unsetFoo() deletes the property foo.
  • push<PropertyName>: Pushes a value onto an array property.

    • If the property is not already an array, it initializes it as an empty array.
    • Example: $obj->pushFoo($value) adds $value to the array property foo.
  • pop<PropertyName>: Pops a value from an array property.

    • Returns the last value from the array property or null if it doesn't exist.
    • Example: $value = $obj->popFoo() removes and returns the last value from the array property foo.

Parameters

$method

Method name that was called.

$params

Parameters passed to the method.

Return

mixed|null

The result of the method call or null if the method does not return a value.

14. isSnake

Declaration

private function isSnake() : bool
{
}

Description

Check if the JSON naming strategy is snake case.

Return

bool

True if the naming strategy is snake case, false otherwise.

15. isCamel

Declaration

protected function isCamel() : bool
{
}

Description

Check if the JSON naming strategy is camel case.

Return

bool

True if the naming strategy is camel case, false otherwise.

16. isPretty

Declaration

private function isPretty() : bool
{
}

Description

Check if the JSON should be prettified.

Return

bool

True if prettification is enabled, false otherwise.

17. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation.

This method serializes the object to JSON format, with options for pretty printing based on the configuration. It uses the appropriate naming strategy for properties as specified in the class parameters.

Return

string

The JSON string representation of the object.

MagicObject\Txt

Declaration

class Txt { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class Txt

A utility class that provides dynamic handling of static method calls and dynamic property access. This class allows for flexible interaction by returning the names of methods and properties that are called statically or accessed dynamically but are not explicitly defined within the class. It can be useful for implementing dynamic behavior or creating a fluent interface.

Example

 <?php
 echo Txt::planetbiru(); // Will print "planetbiru"
 echo Txt::of()->planetbiru; // Will print "planetbiru"
 echo Txt::getInstance()->planetbiru; // Will print "planetbiru"

Methods

1. __callStatic

Declaration

public static function __callStatic(
    string $name,
    array $arguments
) : string
{
}

Description

Handles static calls to undefined methods.

This method intercepts calls to static methods that are not explicitly defined in the class and returns the name of the method being called. It allows for flexible handling of undefined static methods.

Parameters

$name

The name of the method being called.

$arguments

An array of arguments passed to the method.

Return

string

The name of the called method.

2. getInstance

Declaration

public static function getInstance() : Txt
{
}

Description

Returns a new instance of the Txt class.

This method allows you to retrieve an instance of the Txt class for non-static operations. This instance can be used to access dynamic properties via the __get() magic method.

Return

Txt

A new instance of the Txt class.

3. of

Declaration

public static function of() : Txt
{
}

Description

Creates and returns a new instance of the Txt class.

Similar to getInstance(), this method allows you to retrieve an instance of the Txt class for non-static operations, such as dynamic property access using the __get() magic method.

Return

Txt

A new instance of the Txt class.

4. __get

Declaration

public function __get(
    string $name
) : string
{
}

Description

Handles dynamic access to undefined properties.

This method is invoked when an undefined property is accessed on an instance of the Txt class. It returns the name of the property being accessed.

Parameters

$name

The name of the property being accessed.

Return

string

The name of the accessed property.

MagicObject\ComplexNumber\ComplexNumber

Declaration

class ComplexNumber { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

ComplexNumber class

Properties

1. real

Declaration

private float $real;

Description

Real part of the complex number.

2. imaginary

Declaration

private float $imaginary;

Description

Imaginary part of the complex number.

Methods

1. __construct

Declaration

public function __construct(
    float $real,
    float $imaginary
)
{
}

Description

Constructor to initialize the complex number.

Parameters

$real

Real part of the complex number.

$imaginary

Imaginary part of the complex number.

2. add

Declaration

public function add(
    self $self
) : self
{
}

Description

Add another complex number to this one.

Parameters

$self

The complex number to add.

Return

self

The sum of the two complex numbers.

3. subtract

Declaration

public function subtract(
    self $self
) : self
{
}

Description

Subtract another complex number from this one.

Parameters

$self

The complex number to subtract.

Return

self

The result of the subtraction.

4. multiply

Declaration

public function multiply(
    self $self
) : self
{
}

Description

Multiply this complex number by another.

Parameters

$self

The complex number to multiply.

Return

self

The product of the two complex numbers.

5. divide

Declaration

public function divide(
    self $self
) : self
{
}

Description

Divide this complex number by another.

Parameters

$self

The complex number to divide by.

Return

self

The result of the division.

6. magnitude

Declaration

public function magnitude() : float
{
}

Description

Get the magnitude of the complex number.

Return

float

The magnitude of the complex number.

7. conjugate

Declaration

public function conjugate() : self
{
}

Description

Get the conjugate of the complex number.

Return

self

The conjugate of the complex number.

8. __toString

Declaration

public function __toString() : string
{
}

Description

String representation of the complex number.

Return

string

The complex number as a string.

9. getReal

Declaration

public function getReal() : float
{
}

Description

Get the real part of the complex number.

Return

float

The real part.

10. setReal

Declaration

public function setReal(
    float $real
) : self
{
}

Description

Set the real part of the complex number.

Parameters

$real

The real part.

Return

self

Returns the current instance for method chaining.

11. getImaginary

Declaration

public function getImaginary() : float
{
}

Description

Get the imaginary part of the complex number.

Return

float

The imaginary part.

12. setImaginary

Declaration

public function setImaginary(
    float $imaginary
) : self
{
}

Description

Set the imaginary part of the complex number.

Parameters

$imaginary

The imaginary part.

Return

self

Returns the current instance for method chaining.

MagicObject\Constants\PicoHttpStatus

Declaration

class PicoHttpStatus { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoHttpStatus

This class defines constants for standard HTTP status codes.

Constants

const HTTP_CONTINUE = 100;
const HTTP_SWITCH_PROTOCOLS = 101;
const HTTP_OK = 200;
const HTTP_CREATED = 201;
const HTTP_ACCEPTED = 202;
const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
const HTTP_NO_CONTENT = 204;
const HTTP_RESET_CONTENT = 205;
const HTTP_PARTIAL_CONTENT = 206;
const HTTP_MULTIPLE_CHOICES = 300;
const HTTP_MOVED_PERMANENTLY = 301;
const HTTP_MOVED_TEMPORARILY = 302;
const HTTP_SEE_OTHER = 303;
const HTTP_NOT_MODIFIED = 304;
const HTTP_USE_PROXY = 305;
const HTTP_BAD_REQUEST = 400;
const HTTP_UNAUTHORIZED = 401;
const HTTP_PAYMENT_REQUIRED = 402;
const HTTP_FORBIDDEN = 403;
const HTTP_NOT_FOUND = 404;
const HTTP_METHOD_NOT_ALLOWED = 405;
const HTTP_NOT_ACCEPTABLE = 406;
const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
const HTTP_REQUEST_TIME_OUT = 408;
const HTTP_CONFLICT = 409;
const HTTP_GONE = 410;
const HTTP_LENGTH_REQUIRED = 411;
const HTTP_PRECONDITION_FAILED = 412;
const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
const HTTP_REQUEST_URI_TOO_LARGE = 414;
const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
const HTTP_INTERNAL_SERVER_ERROR = 500;
const HTTP_NOT_IMPLEMENTED = 501;
const HTTP_BAD_GATEWAY = 502;
const HTTP_SERVICE_UNAVAILABLE = 503;
const HTTP_GATEWAY_TIME_OUT = 504;
const HTTP_HTTP_VERSION_NOT_SUPPORTED = 505;

Properties

1. httpStatus

Declaration

public array $httpStatus = array ( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Moved Temporarily', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', );

Description

HTTP status codes and their respective messages.

This array holds the standard HTTP status codes along with their descriptions. It can be used to provide meaningful responses in HTTP communication.

MagicObject\Constants\PicoMime

Declaration

class PicoMime { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoMime

This class contains constants representing various MIME types.

Constants

const APPLICATION_STEP = "application/STEP";
const APPLICATION_ANDREW_INSET = "application/andrew-inset";
const APPLICATION_APPINSTALLER = "application/appinstaller";
const APPLICATION_APPLIXWARE = "application/applixware";
const APPLICATION_APPX = "application/appx";
const APPLICATION_APPXBUNDLE = "application/appxbundle";
const APPLICATION_ATOM_XML = "application/atom+xml";
const APPLICATION_ATOMCAT_XML = "application/atomcat+xml";
const APPLICATION_ATOMDELETED_XML = "application/atomdeleted+xml";
const APPLICATION_ATOMSVC_XML = "application/atomsvc+xml";
const APPLICATION_ATSC_DWD_XML = "application/atsc-dwd+xml";
const APPLICATION_ATSC_HELD_XML = "application/atsc-held+xml";
const APPLICATION_ATSC_RSAT_XML = "application/atsc-rsat+xml";
const APPLICATION_AUTOMATIONML_AML_XML = "application/automationml-aml+xml";
const APPLICATION_AUTOMATIONML_AMLX_ZIP = "application/automationml-amlx+zip";
const APPLICATION_BRAILLE = "application/braille";
const APPLICATION_CALENDAR_XML = "application/calendar+xml";
const APPLICATION_CCXML_XML = "application/ccxml+xml";
const APPLICATION_CDFX_XML = "application/cdfx+xml";
const APPLICATION_CDMI_CAPABILITY = "application/cdmi-capability";
const APPLICATION_CDMI_CONTAINER = "application/cdmi-container";
const APPLICATION_CDMI_DOMAIN = "application/cdmi-domain";
const APPLICATION_CDMI_OBJECT = "application/cdmi-object";
const APPLICATION_CDMI_QUEUE = "application/cdmi-queue";
const APPLICATION_CDR = "application/cdr";
const APPLICATION_CPL_XML = "application/cpl+xml";
const APPLICATION_CU_SEEME = "application/cu-seeme";
const APPLICATION_CWL = "application/cwl";
const APPLICATION_DASH_XML = "application/dash+xml";
const APPLICATION_DAVMOUNT_XML = "application/davmount+xml";
const APPLICATION_DOCBOOK_XML = "application/docbook+xml";
const APPLICATION_DSSC_DER = "application/dssc+der";
const APPLICATION_DSSC_XML = "application/dssc+xml";
const APPLICATION_ECMASCRIPT = "application/ecmascript";
const APPLICATION_EMMA_XML = "application/emma+xml";
const APPLICATION_EMOTIONML_XML = "application/emotionml+xml";
const APPLICATION_EPUB_ZIP = "application/epub+zip";
const APPLICATION_EXCEL = "application/excel";
const APPLICATION_EXI = "application/exi";
const APPLICATION_EXPRESS = "application/express";
const APPLICATION_FDT_XML = "application/fdt+xml";
const APPLICATION_FONT_TDPFR = "application/font-tdpfr";
const APPLICATION_GEO_JSON = "application/geo+json";
const APPLICATION_GML_XML = "application/gml+xml";
const APPLICATION_GPG_KEYS = "application/gpg-keys";
const APPLICATION_GPX_XML = "application/gpx+xml";
const APPLICATION_GXF = "application/gxf";
const APPLICATION_GZIP = "application/gzip";
const APPLICATION_HJSON = "application/hjson";
const APPLICATION_HYPERSTUDIO = "application/hyperstudio";
const APPLICATION_INKML_XML = "application/inkml+xml";
const APPLICATION_IPFIX = "application/ipfix";
const APPLICATION_ITS_XML = "application/its+xml";
const APPLICATION_JAVA_ARCHIVE = "application/java-archive";
const APPLICATION_JAVA_SERIALIZED_OBJECT = "application/java-serialized-object";
const APPLICATION_JAVASCRIPT = "application/javascript";
const APPLICATION_JSON = "application/json";
const APPLICATION_JSON5 = "application/json5";
const APPLICATION_JSONML_JSON = "application/jsonml+json";
const APPLICATION_LD_JSON = "application/ld+json";
const APPLICATION_LGR_XML = "application/lgr+xml";
const APPLICATION_LOST_XML = "application/lost+xml";
const APPLICATION_MAC_BINHEX40 = "application/mac-binhex40";
const APPLICATION_MAC_COMPACTPRO = "application/mac-compactpro";
const APPLICATION_MADS_XML = "application/mads+xml";
const APPLICATION_MANIFEST_JSON = "application/manifest+json";
const APPLICATION_MARC = "application/marc";
const APPLICATION_MARCXML_XML = "application/marcxml+xml";
const APPLICATION_MATHEMATICA = "application/mathematica";
const APPLICATION_MATHML_XML = "application/mathml+xml";
const APPLICATION_MBOX = "application/mbox";
const APPLICATION_MEDIA_POLICY_DATASET_XML = "application/media-policy-dataset+xml";
const APPLICATION_MEDIASERVERCONTROL_XML = "application/mediaservercontrol+xml";
const APPLICATION_METALINK_XML = "application/metalink+xml";
const APPLICATION_METALINK4_XML = "application/metalink4+xml";
const APPLICATION_METS_XML = "application/mets+xml";
const APPLICATION_MMT_AEI_XML = "application/mmt-aei+xml";
const APPLICATION_MMT_USD_XML = "application/mmt-usd+xml";
const APPLICATION_MODS_XML = "application/mods+xml";
const APPLICATION_MP21 = "application/mp21";
const APPLICATION_MP4 = "application/mp4";
const APPLICATION_MSIX = "application/msix";
const APPLICATION_MSIXBUNDLE = "application/msixbundle";
const APPLICATION_MSWORD = "application/msword";
const APPLICATION_MXF = "application/mxf";
const APPLICATION_N_QUADS = "application/n-quads";
const APPLICATION_N_TRIPLES = "application/n-triples";
const APPLICATION_NODE = "application/node";
const APPLICATION_OCTET_STREAM = "application/octet-stream";
const APPLICATION_ODA = "application/oda";
const APPLICATION_OEBPS_PACKAGE_XML = "application/oebps-package+xml";
const APPLICATION_OGG = "application/ogg";
const APPLICATION_OMDOC_XML = "application/omdoc+xml";
const APPLICATION_ONENOTE = "application/onenote";
const APPLICATION_OXPS = "application/oxps";
const APPLICATION_P2P_OVERLAY_XML = "application/p2p-overlay+xml";
const APPLICATION_PATCH_OPS_ERROR_XML = "application/patch-ops-error+xml";
const APPLICATION_PDF = "application/pdf";
const APPLICATION_PGP = "application/pgp";
const APPLICATION_PGP_SIGNATURE = "application/pgp-signature";
const APPLICATION_PICS_RULES = "application/pics-rules";
const APPLICATION_PKCS7_MIME = "application/pkcs7-mime";
const APPLICATION_PKCS7_SIGNATURE = "application/pkcs7-signature";
const APPLICATION_PKCS8 = "application/pkcs8";
const APPLICATION_PKIX_CERT = "application/pkix-cert";
const APPLICATION_PKIX_CRL = "application/pkix-crl";
const APPLICATION_PKIX_PKIPATH = "application/pkix-pkipath";
const APPLICATION_PKIXCMP = "application/pkixcmp";
const APPLICATION_PLS_XML = "application/pls+xml";
const APPLICATION_POSTSCRIPT = "application/postscript";
const APPLICATION_POWERPOINT = "application/powerpoint";
const APPLICATION_PROVENANCE_XML = "application/provenance+xml";
const APPLICATION_PRS_CWW = "application/prs.cww";
const APPLICATION_PRS_XSF_XML = "application/prs.xsf+xml";
const APPLICATION_PSKC_XML = "application/pskc+xml";
const APPLICATION_RAML_YAML = "application/raml+yaml";
const APPLICATION_RDF_XML = "application/rdf+xml";
const APPLICATION_REGINFO_XML = "application/reginfo+xml";
const APPLICATION_RELAX_NG_COMPACT_SYNTAX = "application/relax-ng-compact-syntax";
const APPLICATION_RESOURCE_LISTS_XML = "application/resource-lists+xml";
const APPLICATION_RESOURCE_LISTS_DIFF_XML = "application/resource-lists-diff+xml";
const APPLICATION_RLS_SERVICES_XML = "application/rls-services+xml";
const APPLICATION_ROUTE_APD_XML = "application/route-apd+xml";
const APPLICATION_ROUTE_S_TSID_XML = "application/route-s-tsid+xml";
const APPLICATION_ROUTE_USD_XML = "application/route-usd+xml";
const APPLICATION_RPKI_GHOSTBUSTERS = "application/rpki-ghostbusters";
const APPLICATION_RPKI_MANIFEST = "application/rpki-manifest";
const APPLICATION_RPKI_ROA = "application/rpki-roa";
const APPLICATION_RSD_XML = "application/rsd+xml";
const APPLICATION_RSS_XML = "application/rss+xml";
const APPLICATION_SBML_XML = "application/sbml+xml";
const APPLICATION_SCVP_CV_REQUEST = "application/scvp-cv-request";
const APPLICATION_SCVP_CV_RESPONSE = "application/scvp-cv-response";
const APPLICATION_SCVP_VP_REQUEST = "application/scvp-vp-request";
const APPLICATION_SCVP_VP_RESPONSE = "application/scvp-vp-response";
const APPLICATION_SDP = "application/sdp";
const APPLICATION_SENML_XML = "application/senml+xml";
const APPLICATION_SENSML_XML = "application/sensml+xml";
const APPLICATION_SET_PAYMENT_INITIATION = "application/set-payment-initiation";
const APPLICATION_SET_REGISTRATION_INITIATION = "application/set-registration-initiation";
const APPLICATION_SHF_XML = "application/shf+xml";
const APPLICATION_SIEVE = "application/sieve";
const APPLICATION_SMIL = "application/smil";
const APPLICATION_SPARQL_QUERY = "application/sparql-query";
const APPLICATION_SPARQL_RESULTS_XML = "application/sparql-results+xml";
const APPLICATION_SRGS = "application/srgs";
const APPLICATION_SRGS_XML = "application/srgs+xml";
const APPLICATION_SRU_XML = "application/sru+xml";
const APPLICATION_SSDL_XML = "application/ssdl+xml";
const APPLICATION_SSML_XML = "application/ssml+xml";
const APPLICATION_SWID_XML = "application/swid+xml";
const APPLICATION_TEI_XML = "application/tei+xml";
const APPLICATION_THRAUD_XML = "application/thraud+xml";
const APPLICATION_TIMESTAMPED_DATA = "application/timestamped-data";
const APPLICATION_TOML = "application/toml";
const APPLICATION_TRIG = "application/trig";
const APPLICATION_TTML_XML = "application/ttml+xml";
const APPLICATION_UBJSON = "application/ubjson";
const APPLICATION_URC_RESSHEET_XML = "application/urc-ressheet+xml";
const APPLICATION_URC_TARGETDESC_XML = "application/urc-targetdesc+xml";
const APPLICATION_VIDEOLAN = "application/videolan";
const APPLICATION_VND_1000MINDS_DECISION_MODEL_XML = "application/vnd.1000minds.decision-model+xml";
const APPLICATION_VND_3GPP_PIC_BW_LARGE = "application/vnd.3gpp.pic-bw-large";
const APPLICATION_VND_3GPP_PIC_BW_SMALL = "application/vnd.3gpp.pic-bw-small";
const APPLICATION_VND_3GPP_PIC_BW_VAR = "application/vnd.3gpp.pic-bw-var";
const APPLICATION_VND_3GPP2_TCAP = "application/vnd.3gpp2.tcap";
const APPLICATION_VND_3M_POST_IT_NOTES = "application/vnd.3m.post-it-notes";
const APPLICATION_VND_ACCPAC_SIMPLY_ASO = "application/vnd.accpac.simply.aso";
const APPLICATION_VND_ACCPAC_SIMPLY_IMP = "application/vnd.accpac.simply.imp";
const APPLICATION_VND_ACUCOBOL = "application/vnd.acucobol";
const APPLICATION_VND_ACUCORP = "application/vnd.acucorp";
const APPLICATION_VND_ADOBE_AIR_APPLICATION_INSTALLER_PACKAGE_ZIP = "application/vnd.adobe.air-application-installer-package+zip";
const APPLICATION_VND_ADOBE_FORMSCENTRAL_FCDT = "application/vnd.adobe.formscentral.fcdt";
const APPLICATION_VND_ADOBE_FXP = "application/vnd.adobe.fxp";
const APPLICATION_VND_ADOBE_XDP_XML = "application/vnd.adobe.xdp+xml";
const APPLICATION_VND_AGE = "application/vnd.age";
const APPLICATION_VND_AHEAD_SPACE = "application/vnd.ahead.space";
const APPLICATION_VND_AIRZIP_FILESECURE_AZF = "application/vnd.airzip.filesecure.azf";
const APPLICATION_VND_AIRZIP_FILESECURE_AZS = "application/vnd.airzip.filesecure.azs";
const APPLICATION_VND_AMAZON_EBOOK = "application/vnd.amazon.ebook";
const APPLICATION_VND_AMERICANDYNAMICS_ACC = "application/vnd.americandynamics.acc";
const APPLICATION_VND_AMIGA_AMI = "application/vnd.amiga.ami";
const APPLICATION_VND_ANDROID_PACKAGE_ARCHIVE = "application/vnd.android.package-archive";
const APPLICATION_VND_ANSER_WEB_CERTIFICATE_ISSUE_INITIATION = "application/vnd.anser-web-certificate-issue-initiation";
const APPLICATION_VND_ANSER_WEB_FUNDS_TRANSFER_INITIATION = "application/vnd.anser-web-funds-transfer-initiation";
const APPLICATION_VND_ANTIX_GAME_COMPONENT = "application/vnd.antix.game-component";
const APPLICATION_VND_APPLE_INSTALLER_XML = "application/vnd.apple.installer+xml";
const APPLICATION_VND_APPLE_MPEGURL = "application/vnd.apple.mpegurl";
const APPLICATION_VND_APPLE_PKPASS = "application/vnd.apple.pkpass";
const APPLICATION_VND_ARISTANETWORKS_SWI = "application/vnd.aristanetworks.swi";
const APPLICATION_VND_ASTRAEA_SOFTWARE_IOTA = "application/vnd.astraea-software.iota";
const APPLICATION_VND_AUDIOGRAPH = "application/vnd.audiograph";
const APPLICATION_VND_BALSAMIQ_BMML_XML = "application/vnd.balsamiq.bmml+xml";
const APPLICATION_VND_BLUEICE_MULTIPASS = "application/vnd.blueice.multipass";
const APPLICATION_VND_BMI = "application/vnd.bmi";
const APPLICATION_VND_BUSINESSOBJECTS = "application/vnd.businessobjects";
const APPLICATION_VND_CHEMDRAW_XML = "application/vnd.chemdraw+xml";
const APPLICATION_VND_CHIPNUTS_KARAOKE_MMD = "application/vnd.chipnuts.karaoke-mmd";
const APPLICATION_VND_CINDERELLA = "application/vnd.cinderella";
const APPLICATION_VND_CITATIONSTYLES_STYLE_XML = "application/vnd.citationstyles.style+xml";
const APPLICATION_VND_CLAYMORE = "application/vnd.claymore";
const APPLICATION_VND_CLOANTO_RP9 = "application/vnd.cloanto.rp9";
const APPLICATION_VND_CLONK_C4GROUP = "application/vnd.clonk.c4group";
const APPLICATION_VND_CLUETRUST_CARTOMOBILE_CONFIG = "application/vnd.cluetrust.cartomobile-config";
const APPLICATION_VND_CLUETRUST_CARTOMOBILE_CONFIG_PKG = "application/vnd.cluetrust.cartomobile-config-pkg";
const APPLICATION_VND_COMMONSPACE = "application/vnd.commonspace";
const APPLICATION_VND_CONTACT_CMSG = "application/vnd.contact.cmsg";
const APPLICATION_VND_COSMOCALLER = "application/vnd.cosmocaller";
const APPLICATION_VND_CRICK_CLICKER = "application/vnd.crick.clicker";
const APPLICATION_VND_CRICK_CLICKER_KEYBOARD = "application/vnd.crick.clicker.keyboard";
const APPLICATION_VND_CRICK_CLICKER_PALETTE = "application/vnd.crick.clicker.palette";
const APPLICATION_VND_CRICK_CLICKER_TEMPLATE = "application/vnd.crick.clicker.template";
const APPLICATION_VND_CRICK_CLICKER_WORDBANK = "application/vnd.crick.clicker.wordbank";
const APPLICATION_VND_CRITICALTOOLS_WBS_XML = "application/vnd.criticaltools.wbs+xml";
const APPLICATION_VND_CTC_POSML = "application/vnd.ctc-posml";
const APPLICATION_VND_CUPS_PPD = "application/vnd.cups-ppd";
const APPLICATION_VND_CURL_CAR = "application/vnd.curl.car";
const APPLICATION_VND_CURL_PCURL = "application/vnd.curl.pcurl";
const APPLICATION_VND_DART = "application/vnd.dart";
const APPLICATION_VND_DATA_VISION_RDZ = "application/vnd.data-vision.rdz";
const APPLICATION_VND_DBF = "application/vnd.dbf";
const APPLICATION_VND_DECE_DATA = "application/vnd.dece.data";
const APPLICATION_VND_DECE_TTML_XML = "application/vnd.dece.ttml+xml";
const APPLICATION_VND_DECE_UNSPECIFIED = "application/vnd.dece.unspecified";
const APPLICATION_VND_DECE_ZIP = "application/vnd.dece.zip";
const APPLICATION_VND_DENOVO_FCSELAYOUT_LINK = "application/vnd.denovo.fcselayout-link";
const APPLICATION_VND_DNA = "application/vnd.dna";
const APPLICATION_VND_DOLBY_MLP = "application/vnd.dolby.mlp";
const APPLICATION_VND_DPGRAPH = "application/vnd.dpgraph";
const APPLICATION_VND_DREAMFACTORY = "application/vnd.dreamfactory";
const APPLICATION_VND_DS_KEYPOINT = "application/vnd.ds-keypoint";
const APPLICATION_VND_DVB_AIT = "application/vnd.dvb.ait";
const APPLICATION_VND_DVB_SERVICE = "application/vnd.dvb.service";
const APPLICATION_VND_DYNAGEO = "application/vnd.dynageo";
const APPLICATION_VND_ECOWIN_CHART = "application/vnd.ecowin.chart";
const APPLICATION_VND_ENLIVEN = "application/vnd.enliven";
const APPLICATION_VND_EPSON_ESF = "application/vnd.epson.esf";
const APPLICATION_VND_EPSON_MSF = "application/vnd.epson.msf";
const APPLICATION_VND_EPSON_QUICKANIME = "application/vnd.epson.quickanime";
const APPLICATION_VND_EPSON_SALT = "application/vnd.epson.salt";
const APPLICATION_VND_EPSON_SSF = "application/vnd.epson.ssf";
const APPLICATION_VND_ESZIGNO3_XML = "application/vnd.eszigno3+xml";
const APPLICATION_VND_EZPIX_ALBUM = "application/vnd.ezpix-album";
const APPLICATION_VND_EZPIX_PACKAGE = "application/vnd.ezpix-package";
const APPLICATION_VND_FDF = "application/vnd.fdf";
const APPLICATION_VND_FDSN_MSEED = "application/vnd.fdsn.mseed";
const APPLICATION_VND_FDSN_SEED = "application/vnd.fdsn.seed";
const APPLICATION_VND_FLOGRAPHIT = "application/vnd.flographit";
const APPLICATION_VND_FLUXTIME_CLIP = "application/vnd.fluxtime.clip";
const APPLICATION_VND_FRAMEMAKER = "application/vnd.framemaker";
const APPLICATION_VND_FROGANS_FNC = "application/vnd.frogans.fnc";
const APPLICATION_VND_FROGANS_LTF = "application/vnd.frogans.ltf";
const APPLICATION_VND_FSC_WEBLAUNCH = "application/vnd.fsc.weblaunch";
const APPLICATION_VND_FUJITSU_OASYS = "application/vnd.fujitsu.oasys";
const APPLICATION_VND_FUJITSU_OASYS2 = "application/vnd.fujitsu.oasys2";
const APPLICATION_VND_FUJITSU_OASYS3 = "application/vnd.fujitsu.oasys3";
const APPLICATION_VND_FUJITSU_OASYSGP = "application/vnd.fujitsu.oasysgp";
const APPLICATION_VND_FUJITSU_OASYSPRS = "application/vnd.fujitsu.oasysprs";
const APPLICATION_VND_FUJIXEROX_DDD = "application/vnd.fujixerox.ddd";
const APPLICATION_VND_FUJIXEROX_DOCUWORKS = "application/vnd.fujixerox.docuworks";
const APPLICATION_VND_FUJIXEROX_DOCUWORKS_BINDER = "application/vnd.fujixerox.docuworks.binder";
const APPLICATION_VND_FUZZYSHEET = "application/vnd.fuzzysheet";
const APPLICATION_VND_GENOMATIX_TUXEDO = "application/vnd.genomatix.tuxedo";
const APPLICATION_VND_GEOGEBRA_FILE = "application/vnd.geogebra.file";
const APPLICATION_VND_GEOGEBRA_TOOL = "application/vnd.geogebra.tool";
const APPLICATION_VND_GEOMETRY_EXPLORER = "application/vnd.geometry-explorer";
const APPLICATION_VND_GEONEXT = "application/vnd.geonext";
const APPLICATION_VND_GEOPLAN = "application/vnd.geoplan";
const APPLICATION_VND_GEOSPACE = "application/vnd.geospace";
const APPLICATION_VND_GMX = "application/vnd.gmx";
const APPLICATION_VND_GOOGLE_APPS_DOCUMENT = "application/vnd.google-apps.document";
const APPLICATION_VND_GOOGLE_APPS_PRESENTATION = "application/vnd.google-apps.presentation";
const APPLICATION_VND_GOOGLE_APPS_SPREADSHEET = "application/vnd.google-apps.spreadsheet";
const APPLICATION_VND_GOOGLE_EARTH_KML_XML = "application/vnd.google-earth.kml+xml";
const APPLICATION_VND_GOOGLE_EARTH_KMZ = "application/vnd.google-earth.kmz";
const APPLICATION_VND_GRAFEQ = "application/vnd.grafeq";
const APPLICATION_VND_GROOVE_ACCOUNT = "application/vnd.groove-account";
const APPLICATION_VND_GROOVE_HELP = "application/vnd.groove-help";
const APPLICATION_VND_GROOVE_IDENTITY_MESSAGE = "application/vnd.groove-identity-message";
const APPLICATION_VND_GROOVE_INJECTOR = "application/vnd.groove-injector";
const APPLICATION_VND_GROOVE_TOOL_MESSAGE = "application/vnd.groove-tool-message";
const APPLICATION_VND_GROOVE_TOOL_TEMPLATE = "application/vnd.groove-tool-template";
const APPLICATION_VND_GROOVE_VCARD = "application/vnd.groove-vcard";
const APPLICATION_VND_HAL_XML = "application/vnd.hal+xml";
const APPLICATION_VND_HANDHELD_ENTERTAINMENT_XML = "application/vnd.handheld-entertainment+xml";
const APPLICATION_VND_HBCI = "application/vnd.hbci";
const APPLICATION_VND_HHE_LESSON_PLAYER = "application/vnd.hhe.lesson-player";
const APPLICATION_VND_HP_HPGL = "application/vnd.hp-hpgl";
const APPLICATION_VND_HP_HPID = "application/vnd.hp-hpid";
const APPLICATION_VND_HP_HPS = "application/vnd.hp-hps";
const APPLICATION_VND_HP_JLYT = "application/vnd.hp-jlyt";
const APPLICATION_VND_HP_PCL = "application/vnd.hp-pcl";
const APPLICATION_VND_HP_PCLXL = "application/vnd.hp-pclxl";
const APPLICATION_VND_HYDROSTATIX_SOF_DATA = "application/vnd.hydrostatix.sof-data";
const APPLICATION_VND_IBM_MINIPAY = "application/vnd.ibm.minipay";
const APPLICATION_VND_IBM_MODCAP = "application/vnd.ibm.modcap";
const APPLICATION_VND_IBM_RIGHTS_MANAGEMENT = "application/vnd.ibm.rights-management";
const APPLICATION_VND_IBM_SECURE_CONTAINER = "application/vnd.ibm.secure-container";
const APPLICATION_VND_ICCPROFILE = "application/vnd.iccprofile";
const APPLICATION_VND_IGLOADER = "application/vnd.igloader";
const APPLICATION_VND_IMMERVISION_IVP = "application/vnd.immervision-ivp";
const APPLICATION_VND_IMMERVISION_IVU = "application/vnd.immervision-ivu";
const APPLICATION_VND_INSORS_IGM = "application/vnd.insors.igm";
const APPLICATION_VND_INTERCON_FORMNET = "application/vnd.intercon.formnet";
const APPLICATION_VND_INTERGEO = "application/vnd.intergeo";
const APPLICATION_VND_INTU_QBO = "application/vnd.intu.qbo";
const APPLICATION_VND_INTU_QFX = "application/vnd.intu.qfx";
const APPLICATION_VND_IPUNPLUGGED_RCPROFILE = "application/vnd.ipunplugged.rcprofile";
const APPLICATION_VND_IREPOSITORY_PACKAGE_XML = "application/vnd.irepository.package+xml";
const APPLICATION_VND_IS_XPR = "application/vnd.is-xpr";
const APPLICATION_VND_ISAC_FCS = "application/vnd.isac.fcs";
const APPLICATION_VND_JAM = "application/vnd.jam";
const APPLICATION_VND_JCP_JAVAME_MIDLET_RMS = "application/vnd.jcp.javame.midlet-rms";
const APPLICATION_VND_JISP = "application/vnd.jisp";
const APPLICATION_VND_JOOST_JODA_ARCHIVE = "application/vnd.joost.joda-archive";
const APPLICATION_VND_KAHOOTZ = "application/vnd.kahootz";
const APPLICATION_VND_KDE_KARBON = "application/vnd.kde.karbon";
const APPLICATION_VND_KDE_KCHART = "application/vnd.kde.kchart";
const APPLICATION_VND_KDE_KFORMULA = "application/vnd.kde.kformula";
const APPLICATION_VND_KDE_KIVIO = "application/vnd.kde.kivio";
const APPLICATION_VND_KDE_KONTOUR = "application/vnd.kde.kontour";
const APPLICATION_VND_KDE_KPRESENTER = "application/vnd.kde.kpresenter";
const APPLICATION_VND_KDE_KSPREAD = "application/vnd.kde.kspread";
const APPLICATION_VND_KDE_KWORD = "application/vnd.kde.kword";
const APPLICATION_VND_KENAMEAAPP = "application/vnd.kenameaapp";
const APPLICATION_VND_KIDSPIRATION = "application/vnd.kidspiration";
const APPLICATION_VND_KINAR = "application/vnd.kinar";
const APPLICATION_VND_KOAN = "application/vnd.koan";
const APPLICATION_VND_KODAK_DESCRIPTOR = "application/vnd.kodak-descriptor";
const APPLICATION_VND_LAS_LAS_XML = "application/vnd.las.las+xml";
const APPLICATION_VND_LLAMAGRAPHICS_LIFE_BALANCE_DESKTOP = "application/vnd.llamagraphics.life-balance.desktop";
const APPLICATION_VND_LLAMAGRAPHICS_LIFE_BALANCE_EXCHANGE_XML = "application/vnd.llamagraphics.life-balance.exchange+xml";
const APPLICATION_VND_LOTUS_1_2_3 = "application/vnd.lotus-1-2-3";
const APPLICATION_VND_LOTUS_APPROACH = "application/vnd.lotus-approach";
const APPLICATION_VND_LOTUS_FREELANCE = "application/vnd.lotus-freelance";
const APPLICATION_VND_LOTUS_NOTES = "application/vnd.lotus-notes";
const APPLICATION_VND_LOTUS_SCREENCAM = "application/vnd.lotus-screencam";
const APPLICATION_VND_LOTUS_WORDPRO = "application/vnd.lotus-wordpro";
const APPLICATION_VND_MACPORTS_PORTPKG = "application/vnd.macports.portpkg";
const APPLICATION_VND_MAPBOX_VECTOR_TILE = "application/vnd.mapbox-vector-tile";
const APPLICATION_VND_MCD = "application/vnd.mcd";
const APPLICATION_VND_MEDCALCDATA = "application/vnd.medcalcdata";
const APPLICATION_VND_MEDIASTATION_CDKEY = "application/vnd.mediastation.cdkey";
const APPLICATION_VND_MFER = "application/vnd.mfer";
const APPLICATION_VND_MFMP = "application/vnd.mfmp";
const APPLICATION_VND_MICROGRAFX_FLO = "application/vnd.micrografx.flo";
const APPLICATION_VND_MICROGRAFX_IGX = "application/vnd.micrografx.igx";
const APPLICATION_VND_MIF = "application/vnd.mif";
const APPLICATION_VND_MOBIUS_DAF = "application/vnd.mobius.daf";
const APPLICATION_VND_MOBIUS_DIS = "application/vnd.mobius.dis";
const APPLICATION_VND_MOBIUS_MBK = "application/vnd.mobius.mbk";
const APPLICATION_VND_MOBIUS_MQY = "application/vnd.mobius.mqy";
const APPLICATION_VND_MOBIUS_MSL = "application/vnd.mobius.msl";
const APPLICATION_VND_MOBIUS_PLC = "application/vnd.mobius.plc";
const APPLICATION_VND_MOBIUS_TXF = "application/vnd.mobius.txf";
const APPLICATION_VND_MOPHUN_APPLICATION = "application/vnd.mophun.application";
const APPLICATION_VND_MOPHUN_CERTIFICATE = "application/vnd.mophun.certificate";
const APPLICATION_VND_MOZILLA_XUL_XML = "application/vnd.mozilla.xul+xml";
const APPLICATION_VND_MPEGURL = "application/vnd.mpegurl";
const APPLICATION_VND_MS_ARTGALRY = "application/vnd.ms-artgalry";
const APPLICATION_VND_MS_CAB_COMPRESSED = "application/vnd.ms-cab-compressed";
const APPLICATION_VND_MS_EXCEL = "application/vnd.ms-excel";
const APPLICATION_VND_MS_EXCEL_ADDIN_MACROENABLED_12 = "application/vnd.ms-excel.addin.macroEnabled.12";
const APPLICATION_VND_MS_EXCEL_SHEET_BINARY_MACROENABLED_12 = "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
const APPLICATION_VND_MS_EXCEL_SHEET_MACROENABLED_12 = "application/vnd.ms-excel.sheet.macroEnabled.12";
const APPLICATION_VND_MS_EXCEL_TEMPLATE_MACROENABLED_12 = "application/vnd.ms-excel.template.macroEnabled.12";
const APPLICATION_VND_MS_FONTOBJECT = "application/vnd.ms-fontobject";
const APPLICATION_VND_MS_HTMLHELP = "application/vnd.ms-htmlhelp";
const APPLICATION_VND_MS_IMS = "application/vnd.ms-ims";
const APPLICATION_VND_MS_LRM = "application/vnd.ms-lrm";
const APPLICATION_VND_MS_OFFICETHEME = "application/vnd.ms-officetheme";
const APPLICATION_VND_MS_OUTLOOK = "application/vnd.ms-outlook";
const APPLICATION_VND_MS_PKI_SECCAT = "application/vnd.ms-pki.seccat";
const APPLICATION_VND_MS_POWERPOINT = "application/vnd.ms-powerpoint";
const APPLICATION_VND_MS_POWERPOINT_ADDIN_MACROENABLED_12 = "application/vnd.ms-powerpoint.addin.macroEnabled.12";
const APPLICATION_VND_MS_POWERPOINT_PRESENTATION_MACROENABLED_12 = "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
const APPLICATION_VND_MS_POWERPOINT_SLIDE_MACROENABLED_12 = "application/vnd.ms-powerpoint.slide.macroenabled.12";
const APPLICATION_VND_MS_POWERPOINT_SLIDESHOW_MACROENABLED_12 = "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
const APPLICATION_VND_MS_PROJECT = "application/vnd.ms-project";
const APPLICATION_VND_MS_WORD_TEMPLATE_MACROENABLED_12 = "application/vnd.ms-word.template.macroEnabled.12";
const APPLICATION_VND_MS_WORKS = "application/vnd.ms-works";
const APPLICATION_VND_MS_WPL = "application/vnd.ms-wpl";
const APPLICATION_VND_MS_XPSDOCUMENT = "application/vnd.ms-xpsdocument";
const APPLICATION_VND_MSEQ = "application/vnd.mseq";
const APPLICATION_VND_MUSICIAN = "application/vnd.musician";
const APPLICATION_VND_MUVEE_STYLE = "application/vnd.muvee.style";
const APPLICATION_VND_MYNFC = "application/vnd.mynfc";
const APPLICATION_VND_NEUROLANGUAGE_NLU = "application/vnd.neurolanguage.nlu";
const APPLICATION_VND_NITF = "application/vnd.nitf";
const APPLICATION_VND_NOBLENET_DIRECTORY = "application/vnd.noblenet-directory";
const APPLICATION_VND_NOBLENET_SEALER = "application/vnd.noblenet-sealer";
const APPLICATION_VND_NOBLENET_WEB = "application/vnd.noblenet-web";
const APPLICATION_VND_NOKIA_N_GAGE_AC_XML = "application/vnd.nokia.n-gage.ac+xml";
const APPLICATION_VND_NOKIA_N_GAGE_DATA = "application/vnd.nokia.n-gage.data";
const APPLICATION_VND_NOKIA_N_GAGE_SYMBIAN_INSTALL = "application/vnd.nokia.n-gage.symbian.install";
const APPLICATION_VND_NOKIA_RADIO_PRESET = "application/vnd.nokia.radio-preset";
const APPLICATION_VND_NOKIA_RADIO_PRESETS = "application/vnd.nokia.radio-presets";
const APPLICATION_VND_NOVADIGM_EDM = "application/vnd.novadigm.edm";
const APPLICATION_VND_NOVADIGM_EDX = "application/vnd.novadigm.edx";
const APPLICATION_VND_NOVADIGM_EXT = "application/vnd.novadigm.ext";
const APPLICATION_VND_OASIS_OPENDOCUMENT_CHART = "application/vnd.oasis.opendocument.chart";
const APPLICATION_VND_OASIS_OPENDOCUMENT_CHART_TEMPLATE = "application/vnd.oasis.opendocument.chart-template";
const APPLICATION_VND_OASIS_OPENDOCUMENT_DATABASE = "application/vnd.oasis.opendocument.database";
const APPLICATION_VND_OASIS_OPENDOCUMENT_FORMULA = "application/vnd.oasis.opendocument.formula";
const APPLICATION_VND_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE = "application/vnd.oasis.opendocument.formula-template";
const APPLICATION_VND_OASIS_OPENDOCUMENT_GRAPHICS = "application/vnd.oasis.opendocument.graphics";
const APPLICATION_VND_OASIS_OPENDOCUMENT_GRAPHICS_TEMPLATE = "application/vnd.oasis.opendocument.graphics-template";
const APPLICATION_VND_OASIS_OPENDOCUMENT_IMAGE = "application/vnd.oasis.opendocument.image";
const APPLICATION_VND_OASIS_OPENDOCUMENT_IMAGE_TEMPLATE = "application/vnd.oasis.opendocument.image-template";
const APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = "application/vnd.oasis.opendocument.presentation";
const APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE = "application/vnd.oasis.opendocument.presentation-template";
const APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = "application/vnd.oasis.opendocument.spreadsheet";
const APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE = "application/vnd.oasis.opendocument.spreadsheet-template";
const APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = "application/vnd.oasis.opendocument.text";
const APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT_MASTER = "application/vnd.oasis.opendocument.text-master";
const APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT_TEMPLATE = "application/vnd.oasis.opendocument.text-template";
const APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT_WEB = "application/vnd.oasis.opendocument.text-web";
const APPLICATION_VND_OLPC_SUGAR = "application/vnd.olpc-sugar";
const APPLICATION_VND_OMA_DD2_XML = "application/vnd.oma.dd2+xml";
const APPLICATION_VND_OPENBLOX_GAME_XML = "application/vnd.openblox.game+xml";
const APPLICATION_VND_OPENOFFICEORG_EXTENSION = "application/vnd.openofficeorg.extension";
const APPLICATION_VND_OPENSTREETMAP_DATA_XML = "application/vnd.openstreetmap.data+xml";
const APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
const APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_SLIDE = "application/vnd.openxmlformats-officedocument.presentationml.slide";
const APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_SLIDESHOW = "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
const APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_TEMPLATE = "application/vnd.openxmlformats-officedocument.presentationml.template";
const APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
const APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_TEMPLATE = "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
const APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_TEMPLATE = "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
const APPLICATION_VND_OSGEO_MAPGUIDE_PACKAGE = "application/vnd.osgeo.mapguide.package";
const APPLICATION_VND_OSGI_DP = "application/vnd.osgi.dp";
const APPLICATION_VND_OSGI_SUBSYSTEM = "application/vnd.osgi.subsystem";
const APPLICATION_VND_PALM = "application/vnd.palm";
const APPLICATION_VND_PAWAAFILE = "application/vnd.pawaafile";
const APPLICATION_VND_PG_FORMAT = "application/vnd.pg.format";
const APPLICATION_VND_PG_OSASLI = "application/vnd.pg.osasli";
const APPLICATION_VND_PICSEL = "application/vnd.picsel";
const APPLICATION_VND_PMI_WIDGET = "application/vnd.pmi.widget";
const APPLICATION_VND_POCKETLEARN = "application/vnd.pocketlearn";
const APPLICATION_VND_POWERBUILDER6 = "application/vnd.powerbuilder6";
const APPLICATION_VND_PREVIEWSYSTEMS_BOX = "application/vnd.previewsystems.box";
const APPLICATION_VND_PROTEUS_MAGAZINE = "application/vnd.proteus.magazine";
const APPLICATION_VND_PUBLISHARE_DELTA_TREE = "application/vnd.publishare-delta-tree";
const APPLICATION_VND_PVI_PTID1 = "application/vnd.pvi.ptid1";
const APPLICATION_VND_PWG_XHTML_PRINT_XML = "application/vnd.pwg-xhtml-print+xml";
const APPLICATION_VND_QUARK_QUARKXPRESS = "application/vnd.quark.quarkxpress";
const APPLICATION_VND_REALVNC_BED = "application/vnd.realvnc.bed";
const APPLICATION_VND_RECORDARE_MUSICXML = "application/vnd.recordare.musicxml";
const APPLICATION_VND_RECORDARE_MUSICXML_XML = "application/vnd.recordare.musicxml+xml";
const APPLICATION_VND_RIG_CRYPTONOTE = "application/vnd.rig.cryptonote";
const APPLICATION_VND_RIM_COD = "application/vnd.rim.cod";
const APPLICATION_VND_RN_REALMEDIA_VBR = "application/vnd.rn-realmedia-vbr";
const APPLICATION_VND_ROUTE66_LINK66_XML = "application/vnd.route66.link66+xml";
const APPLICATION_VND_SAILINGTRACKER_TRACK = "application/vnd.sailingtracker.track";
const APPLICATION_VND_SEEMAIL = "application/vnd.seemail";
const APPLICATION_VND_SEMA = "application/vnd.sema";
const APPLICATION_VND_SEMD = "application/vnd.semd";
const APPLICATION_VND_SEMF = "application/vnd.semf";
const APPLICATION_VND_SHANA_INFORMED_FORMDATA = "application/vnd.shana.informed.formdata";
const APPLICATION_VND_SHANA_INFORMED_FORMTEMPLATE = "application/vnd.shana.informed.formtemplate";
const APPLICATION_VND_SHANA_INFORMED_INTERCHANGE = "application/vnd.shana.informed.interchange";
const APPLICATION_VND_SHANA_INFORMED_PACKAGE = "application/vnd.shana.informed.package";
const APPLICATION_VND_SIMTECH_MINDMAPPER = "application/vnd.simtech-mindmapper";
const APPLICATION_VND_SMAF = "application/vnd.smaf";
const APPLICATION_VND_SMART_TEACHER = "application/vnd.smart.teacher";
const APPLICATION_VND_SOFTWARE602_FILLER_FORM_XML = "application/vnd.software602.filler.form+xml";
const APPLICATION_VND_SOLENT_SDKM_XML = "application/vnd.solent.sdkm+xml";
const APPLICATION_VND_SPOTFIRE_DXP = "application/vnd.spotfire.dxp";
const APPLICATION_VND_SPOTFIRE_SFS = "application/vnd.spotfire.sfs";
const APPLICATION_VND_STARDIVISION_CALC = "application/vnd.stardivision.calc";
const APPLICATION_VND_STARDIVISION_DRAW = "application/vnd.stardivision.draw";
const APPLICATION_VND_STARDIVISION_IMPRESS = "application/vnd.stardivision.impress";
const APPLICATION_VND_STARDIVISION_MATH = "application/vnd.stardivision.math";
const APPLICATION_VND_STARDIVISION_WRITER = "application/vnd.stardivision.writer";
const APPLICATION_VND_STARDIVISION_WRITER_GLOBAL = "application/vnd.stardivision.writer-global";
const APPLICATION_VND_STEPMANIA_PACKAGE = "application/vnd.stepmania.package";
const APPLICATION_VND_STEPMANIA_STEPCHART = "application/vnd.stepmania.stepchart";
const APPLICATION_VND_SUN_WADL_XML = "application/vnd.sun.wadl+xml";
const APPLICATION_VND_SUN_XML_CALC = "application/vnd.sun.xml.calc";
const APPLICATION_VND_SUN_XML_CALC_TEMPLATE = "application/vnd.sun.xml.calc.template";
const APPLICATION_VND_SUN_XML_DRAW = "application/vnd.sun.xml.draw";
const APPLICATION_VND_SUN_XML_DRAW_TEMPLATE = "application/vnd.sun.xml.draw.template";
const APPLICATION_VND_SUN_XML_IMPRESS = "application/vnd.sun.xml.impress";
const APPLICATION_VND_SUN_XML_IMPRESS_TEMPLATE = "application/vnd.sun.xml.impress.template";
const APPLICATION_VND_SUN_XML_MATH = "application/vnd.sun.xml.math";
const APPLICATION_VND_SUN_XML_WRITER = "application/vnd.sun.xml.writer";
const APPLICATION_VND_SUN_XML_WRITER_GLOBAL = "application/vnd.sun.xml.writer.global";
const APPLICATION_VND_SUN_XML_WRITER_TEMPLATE = "application/vnd.sun.xml.writer.template";
const APPLICATION_VND_SUS_CALENDAR = "application/vnd.sus-calendar";
const APPLICATION_VND_SVD = "application/vnd.svd";
const APPLICATION_VND_SYMBIAN_INSTALL = "application/vnd.symbian.install";
const APPLICATION_VND_SYNCML_XML = "application/vnd.syncml+xml";
const APPLICATION_VND_SYNCML_DM_WBXML = "application/vnd.syncml.dm+wbxml";
const APPLICATION_VND_SYNCML_DM_XML = "application/vnd.syncml.dm+xml";
const APPLICATION_VND_SYNCML_DMDDF_XML = "application/vnd.syncml.dmddf+xml";
const APPLICATION_VND_TAO_INTENT_MODULE_ARCHIVE = "application/vnd.tao.intent-module-archive";
const APPLICATION_VND_TCPDUMP_PCAP = "application/vnd.tcpdump.pcap";
const APPLICATION_VND_TMOBILE_LIVETV = "application/vnd.tmobile-livetv";
const APPLICATION_VND_TRID_TPT = "application/vnd.trid.tpt";
const APPLICATION_VND_TRISCAPE_MXS = "application/vnd.triscape.mxs";
const APPLICATION_VND_TRUEAPP = "application/vnd.trueapp";
const APPLICATION_VND_UFDL = "application/vnd.ufdl";
const APPLICATION_VND_UIQ_THEME = "application/vnd.uiq.theme";
const APPLICATION_VND_UMAJIN = "application/vnd.umajin";
const APPLICATION_VND_UNITY = "application/vnd.unity";
const APPLICATION_VND_UOML_XML = "application/vnd.uoml+xml";
const APPLICATION_VND_VCX = "application/vnd.vcx";
const APPLICATION_VND_VISIO = "application/vnd.visio";
const APPLICATION_VND_VISIONARY = "application/vnd.visionary";
const APPLICATION_VND_VSF = "application/vnd.vsf";
const APPLICATION_VND_WAP_WMLSCRIPTC = "application/vnd.wap.wmlscriptc";
const APPLICATION_VND_WEBTURBO = "application/vnd.webturbo";
const APPLICATION_VND_WOLFRAM_PLAYER = "application/vnd.wolfram.player";
const APPLICATION_VND_WORDPERFECT = "application/vnd.wordperfect";
const APPLICATION_VND_WQD = "application/vnd.wqd";
const APPLICATION_VND_WT_STF = "application/vnd.wt.stf";
const APPLICATION_VND_XARA = "application/vnd.xara";
const APPLICATION_VND_XFDL = "application/vnd.xfdl";
const APPLICATION_VND_YAMAHA_HV_DIC = "application/vnd.yamaha.hv-dic";
const APPLICATION_VND_YAMAHA_HV_SCRIPT = "application/vnd.yamaha.hv-script";
const APPLICATION_VND_YAMAHA_HV_VOICE = "application/vnd.yamaha.hv-voice";
const APPLICATION_VND_YAMAHA_OPENSCOREFORMAT = "application/vnd.yamaha.openscoreformat";
const APPLICATION_VND_YAMAHA_OPENSCOREFORMAT_OSFPVG_XML = "application/vnd.yamaha.openscoreformat.osfpvg+xml";
const APPLICATION_VND_YAMAHA_SMAF_AUDIO = "application/vnd.yamaha.smaf-audio";
const APPLICATION_VND_YAMAHA_SMAF_PHRASE = "application/vnd.yamaha.smaf-phrase";
const APPLICATION_VND_YELLOWRIVER_CUSTOM_MENU = "application/vnd.yellowriver-custom-menu";
const APPLICATION_VND_ZUL = "application/vnd.zul";
const APPLICATION_VND_ZZAZZ_DECK_XML = "application/vnd.zzazz.deck+xml";
const APPLICATION_VOICEXML_XML = "application/voicexml+xml";
const APPLICATION_WASM = "application/wasm";
const APPLICATION_WATCHERINFO_XML = "application/watcherinfo+xml";
const APPLICATION_WBXML = "application/wbxml";
const APPLICATION_WIDGET = "application/widget";
const APPLICATION_WINHLP = "application/winhlp";
const APPLICATION_WMLC = "application/wmlc";
const APPLICATION_WSDL_XML = "application/wsdl+xml";
const APPLICATION_WSPOLICY_XML = "application/wspolicy+xml";
const APPLICATION_X_7Z_COMPRESSED = "application/x-7z-compressed";
const APPLICATION_X_ABIWORD = "application/x-abiword";
const APPLICATION_X_ACE_COMPRESSED = "application/x-ace-compressed";
const APPLICATION_X_APPLE_DISKIMAGE = "application/x-apple-diskimage";
const APPLICATION_X_ARJ = "application/x-arj";
const APPLICATION_X_AUTHORWARE_BIN = "application/x-authorware-bin";
const APPLICATION_X_AUTHORWARE_MAP = "application/x-authorware-map";
const APPLICATION_X_AUTHORWARE_SEG = "application/x-authorware-seg";
const APPLICATION_X_BCPIO = "application/x-bcpio";
const APPLICATION_X_BDOC = "application/x-bdoc";
const APPLICATION_X_BITTORRENT = "application/x-bittorrent";
const APPLICATION_X_BLORB = "application/x-blorb";
const APPLICATION_X_BZIP = "application/x-bzip";
const APPLICATION_X_BZIP2 = "application/x-bzip2";
const APPLICATION_X_CBR = "application/x-cbr";
const APPLICATION_X_CDLINK = "application/x-cdlink";
const APPLICATION_X_CFS_COMPRESSED = "application/x-cfs-compressed";
const APPLICATION_X_CHAT = "application/x-chat";
const APPLICATION_X_CHESS_PGN = "application/x-chess-pgn";
const APPLICATION_X_CHROME_EXTENSION = "application/x-chrome-extension";
const APPLICATION_X_COCOA = "application/x-cocoa";
const APPLICATION_X_COMPRESS = "application/x-compress";
const APPLICATION_X_CONFERENCE = "application/x-conference";
const APPLICATION_X_CPIO = "application/x-cpio";
const APPLICATION_X_CSH = "application/x-csh";
const APPLICATION_X_DEBIAN_PACKAGE = "application/x-debian-package";
const APPLICATION_X_DGC_COMPRESSED = "application/x-dgc-compressed";
const APPLICATION_X_DIRECTOR = "application/x-director";
const APPLICATION_X_DOOM = "application/x-doom";
const APPLICATION_X_DTBNCX_XML = "application/x-dtbncx+xml";
const APPLICATION_X_DTBOOK_XML = "application/x-dtbook+xml";
const APPLICATION_X_DTBRESOURCE_XML = "application/x-dtbresource+xml";
const APPLICATION_X_DVI = "application/x-dvi";
const APPLICATION_X_ENVOY = "application/x-envoy";
const APPLICATION_X_EVA = "application/x-eva";
const APPLICATION_X_FONT_BDF = "application/x-font-bdf";
const APPLICATION_X_FONT_GHOSTSCRIPT = "application/x-font-ghostscript";
const APPLICATION_X_FONT_LINUX_PSF = "application/x-font-linux-psf";
const APPLICATION_X_FONT_PCF = "application/x-font-pcf";
const APPLICATION_X_FONT_SNF = "application/x-font-snf";
const APPLICATION_X_FONT_TYPE1 = "application/x-font-type1";
const APPLICATION_X_FREEARC = "application/x-freearc";
const APPLICATION_X_FUTURESPLASH = "application/x-futuresplash";
const APPLICATION_X_GCA_COMPRESSED = "application/x-gca-compressed";
const APPLICATION_X_GLULX = "application/x-glulx";
const APPLICATION_X_GNUMERIC = "application/x-gnumeric";
const APPLICATION_X_GRAMPS_XML = "application/x-gramps-xml";
const APPLICATION_X_GTAR = "application/x-gtar";
const APPLICATION_X_HDF = "application/x-hdf";
const APPLICATION_X_HTTPD_PHP = "application/x-httpd-php";
const APPLICATION_X_HTTPD_PHP_SOURCE = "application/x-httpd-php-source";
const APPLICATION_X_INSTALL_INSTRUCTIONS = "application/x-install-instructions";
const APPLICATION_X_ISO9660_IMAGE = "application/x-iso9660-image";
const APPLICATION_X_IWORK_KEYNOTE_SFFKEY = "application/x-iwork-keynote-sffkey";
const APPLICATION_X_IWORK_NUMBERS_SFFNUMBERS = "application/x-iwork-numbers-sffnumbers";
const APPLICATION_X_IWORK_PAGES_SFFPAGES = "application/x-iwork-pages-sffpages";
const APPLICATION_X_JAVA_ARCHIVE_DIFF = "application/x-java-archive-diff";
const APPLICATION_X_JAVA_JNLP_FILE = "application/x-java-jnlp-file";
const APPLICATION_X_KEEPASS2 = "application/x-keepass2";
const APPLICATION_X_LATEX = "application/x-latex";
const APPLICATION_X_LUA_BYTECODE = "application/x-lua-bytecode";
const APPLICATION_X_MAKESELF = "application/x-makeself";
const APPLICATION_X_MIE = "application/x-mie";
const APPLICATION_X_MOBIPOCKET_EBOOK = "application/x-mobipocket-ebook";
const APPLICATION_X_MS_APPLICATION = "application/x-ms-application";
const APPLICATION_X_MS_SHORTCUT = "application/x-ms-shortcut";
const APPLICATION_X_MS_WMD = "application/x-ms-wmd";
const APPLICATION_X_MS_XBAP = "application/x-ms-xbap";
const APPLICATION_X_MSACCESS = "application/x-msaccess";
const APPLICATION_X_MSBINDER = "application/x-msbinder";
const APPLICATION_X_MSCARDFILE = "application/x-mscardfile";
const APPLICATION_X_MSCLIP = "application/x-msclip";
const APPLICATION_X_MSDOWNLOAD = "application/x-msdownload";
const APPLICATION_X_MSMEDIAVIEW = "application/x-msmediaview";
const APPLICATION_X_MSMETAFILE = "application/x-msmetafile";
const APPLICATION_X_MSMONEY = "application/x-msmoney";
const APPLICATION_X_MSPUBLISHER = "application/x-mspublisher";
const APPLICATION_X_MSSCHEDULE = "application/x-msschedule";
const APPLICATION_X_MSTERMINAL = "application/x-msterminal";
const APPLICATION_X_MSWRITE = "application/x-mswrite";
const APPLICATION_X_NDJSON = "application/x-ndjson";
const APPLICATION_X_NETCDF = "application/x-netcdf";
const APPLICATION_X_NS_PROXY_AUTOCONFIG = "application/x-ns-proxy-autoconfig";
const APPLICATION_X_NZB = "application/x-nzb";
const APPLICATION_X_PERL = "application/x-perl";
const APPLICATION_X_PHOTOSHOP = "application/x-photoshop";
const APPLICATION_X_PILOT = "application/x-pilot";
const APPLICATION_X_PKCS10 = "application/x-pkcs10";
const APPLICATION_X_PKCS12 = "application/x-pkcs12";
const APPLICATION_X_PKCS7 = "application/x-pkcs7";
const APPLICATION_X_PKCS7_CERTIFICATES = "application/x-pkcs7-certificates";
const APPLICATION_X_PKCS7_CERTREQRESP = "application/x-pkcs7-certreqresp";
const APPLICATION_X_PKCS7_SIGNATURE = "application/x-pkcs7-signature";
const APPLICATION_X_RAR = "application/x-rar";
const APPLICATION_X_RESEARCH_INFO_SYSTEMS = "application/x-research-info-systems";
const APPLICATION_X_SH = "application/x-sh";
const APPLICATION_X_SHAR = "application/x-shar";
const APPLICATION_X_SHOCKWAVE_FLASH = "application/x-shockwave-flash";
const APPLICATION_X_SILVERLIGHT_APP = "application/x-silverlight-app";
const APPLICATION_X_SQL = "application/x-sql";
const APPLICATION_X_STUFFIT = "application/x-stuffit";
const APPLICATION_X_STUFFITX = "application/x-stuffitx";
const APPLICATION_X_SUBRIP = "application/x-subrip";
const APPLICATION_X_SV4CPIO = "application/x-sv4cpio";
const APPLICATION_X_SV4CRC = "application/x-sv4crc";
const APPLICATION_X_T3VM_IMAGE = "application/x-t3vm-image";
const APPLICATION_X_TADS = "application/x-tads";
const APPLICATION_X_TAR = "application/x-tar";
const APPLICATION_X_TCL = "application/x-tcl";
const APPLICATION_X_TEX = "application/x-tex";
const APPLICATION_X_TEX_TFM = "application/x-tex-tfm";
const APPLICATION_X_TEXINFO = "application/x-texinfo";
const APPLICATION_X_USTAR = "application/x-ustar";
const APPLICATION_X_VIRTUALBOX_HDD = "application/x-virtualbox-hdd";
const APPLICATION_X_VIRTUALBOX_OVA = "application/x-virtualbox-ova";
const APPLICATION_X_VIRTUALBOX_OVF = "application/x-virtualbox-ovf";
const APPLICATION_X_VIRTUALBOX_VBOX = "application/x-virtualbox-vbox";
const APPLICATION_X_VIRTUALBOX_VBOX_EXTPACK = "application/x-virtualbox-vbox-extpack";
const APPLICATION_X_VIRTUALBOX_VDI = "application/x-virtualbox-vdi";
const APPLICATION_X_VIRTUALBOX_VHD = "application/x-virtualbox-vhd";
const APPLICATION_X_VIRTUALBOX_VMDK = "application/x-virtualbox-vmdk";
const APPLICATION_X_WAIS_SOURCE = "application/x-wais-source";
const APPLICATION_X_WEB_APP_MANIFEST_JSON = "application/x-web-app-manifest+json";
const APPLICATION_X_X509_CA_CERT = "application/x-x509-ca-cert";
const APPLICATION_X_X509_USER_CERT = "application/x-x509-user-cert";
const APPLICATION_X_XFIG = "application/x-xfig";
const APPLICATION_X_XPINSTALL = "application/x-xpinstall";
const APPLICATION_X_XZ = "application/x-xz";
const APPLICATION_X_ZMACHINE = "application/x-zmachine";
const APPLICATION_XAML_XML = "application/xaml+xml";
const APPLICATION_XCAP_ATT_XML = "application/xcap-att+xml";
const APPLICATION_XCAP_CAPS_XML = "application/xcap-caps+xml";
const APPLICATION_XCAP_DIFF_XML = "application/xcap-diff+xml";
const APPLICATION_XCAP_EL_XML = "application/xcap-el+xml";
const APPLICATION_XCAP_NS_XML = "application/xcap-ns+xml";
const APPLICATION_XENC_XML = "application/xenc+xml";
const APPLICATION_XFDF = "application/xfdf";
const APPLICATION_XHTML_XML = "application/xhtml+xml";
const APPLICATION_XLIFF_XML = "application/xliff+xml";
const APPLICATION_XML = "application/xml";
const APPLICATION_XML_DTD = "application/xml-dtd";
const APPLICATION_XOP_XML = "application/xop+xml";
const APPLICATION_XPROC_XML = "application/xproc+xml";
const APPLICATION_XSLT_XML = "application/xslt+xml";
const APPLICATION_XSPF_XML = "application/xspf+xml";
const APPLICATION_XV_XML = "application/xv+xml";
const APPLICATION_YANG = "application/yang";
const APPLICATION_YIN_XML = "application/yin+xml";
const APPLICATION_ZIP = "application/zip";
const AUDIO_AAC = "audio/aac";
const AUDIO_AC3 = "audio/ac3";
const AUDIO_ACC = "audio/acc";
const AUDIO_ADPCM = "audio/adpcm";
const AUDIO_AMR = "audio/amr";
const AUDIO_BASIC = "audio/basic";
const AUDIO_MIDI = "audio/midi";
const AUDIO_MOBILE_XMF = "audio/mobile-xmf";
const AUDIO_MP4 = "audio/mp4";
const AUDIO_MPEG = "audio/mpeg";
const AUDIO_OGG = "audio/ogg";
const AUDIO_S3M = "audio/s3m";
const AUDIO_SILK = "audio/silk";
const AUDIO_VND_DECE_AUDIO = "audio/vnd.dece.audio";
const AUDIO_VND_DIGITAL_WINDS = "audio/vnd.digital-winds";
const AUDIO_VND_DRA = "audio/vnd.dra";
const AUDIO_VND_DTS = "audio/vnd.dts";
const AUDIO_VND_DTS_HD = "audio/vnd.dts.hd";
const AUDIO_VND_LUCENT_VOICE = "audio/vnd.lucent.voice";
const AUDIO_VND_MS_PLAYREADY_MEDIA_PYA = "audio/vnd.ms-playready.media.pya";
const AUDIO_VND_NUERA_ECELP4800 = "audio/vnd.nuera.ecelp4800";
const AUDIO_VND_NUERA_ECELP7470 = "audio/vnd.nuera.ecelp7470";
const AUDIO_VND_NUERA_ECELP9600 = "audio/vnd.nuera.ecelp9600";
const AUDIO_VND_RIP = "audio/vnd.rip";
const AUDIO_WEBM = "audio/webm";
const AUDIO_X_AIFF = "audio/x-aiff";
const AUDIO_X_AU = "audio/x-au";
const AUDIO_X_CAF = "audio/x-caf";
const AUDIO_X_FLAC = "audio/x-flac";
const AUDIO_X_M4A = "audio/x-m4a";
const AUDIO_X_MATROSKA = "audio/x-matroska";
const AUDIO_X_MS_WAX = "audio/x-ms-wax";
const AUDIO_X_MS_WMA = "audio/x-ms-wma";
const AUDIO_X_PN_REALAUDIO = "audio/x-pn-realaudio";
const AUDIO_X_PN_REALAUDIO_PLUGIN = "audio/x-pn-realaudio-plugin";
const AUDIO_X_REALAUDIO = "audio/x-realaudio";
const AUDIO_X_WAV = "audio/x-wav";
const AUDIO_XM = "audio/xm";
const CHEMICAL_X_CDX = "chemical/x-cdx";
const CHEMICAL_X_CIF = "chemical/x-cif";
const CHEMICAL_X_CMDF = "chemical/x-cmdf";
const CHEMICAL_X_CML = "chemical/x-cml";
const CHEMICAL_X_CSML = "chemical/x-csml";
const CHEMICAL_X_XYZ = "chemical/x-xyz";
const FONT_COLLECTION = "font/collection";
const FONT_OTF = "font/otf";
const FONT_TTF = "font/ttf";
const FONT_WOFF = "font/woff";
const FONT_WOFF2 = "font/woff2";
const IMAGE_ACES = "image/aces";
const IMAGE_APNG = "image/apng";
const IMAGE_AVCI = "image/avci";
const IMAGE_AVCS = "image/avcs";
const IMAGE_AVIF = "image/avif";
const IMAGE_BMP = "image/bmp";
const IMAGE_CGM = "image/cgm";
const IMAGE_DICOM_RLE = "image/dicom-rle";
const IMAGE_DPX = "image/dpx";
const IMAGE_EMF = "image/emf";
const IMAGE_FITS = "image/fits";
const IMAGE_G3FAX = "image/g3fax";
const IMAGE_GIF = "image/gif";
const IMAGE_HEIC = "image/heic";
const IMAGE_HEIC_SEQUENCE = "image/heic-sequence";
const IMAGE_HEIF = "image/heif";
const IMAGE_HEIF_SEQUENCE = "image/heif-sequence";
const IMAGE_HEJ2K = "image/hej2k";
const IMAGE_HSJ2 = "image/hsj2";
const IMAGE_IEF = "image/ief";
const IMAGE_JLS = "image/jls";
const IMAGE_JP2 = "image/jp2";
const IMAGE_JPEG = "image/jpeg";
const IMAGE_JPH = "image/jph";
const IMAGE_JPHC = "image/jphc";
const IMAGE_JPX = "image/jpx";
const IMAGE_JXR = "image/jxr";
const IMAGE_JXRA = "image/jxra";
const IMAGE_JXRS = "image/jxrs";
const IMAGE_JXS = "image/jxs";
const IMAGE_JXSC = "image/jxsc";
const IMAGE_JXSI = "image/jxsi";
const IMAGE_JXSS = "image/jxss";
const IMAGE_KTX = "image/ktx";
const IMAGE_KTX2 = "image/ktx2";
const IMAGE_PNG = "image/png";
const IMAGE_PRS_BTIF = "image/prs.btif";
const IMAGE_PRS_PTI = "image/prs.pti";
const IMAGE_SGI = "image/sgi";
const IMAGE_SVG_XML = "image/svg+xml";
const IMAGE_T38 = "image/t38";
const IMAGE_TIFF = "image/tiff";
const IMAGE_TIFF_FX = "image/tiff-fx";
const IMAGE_VND_AIRZIP_ACCELERATOR_AZV = "image/vnd.airzip.accelerator.azv";
const IMAGE_VND_DECE_GRAPHIC = "image/vnd.dece.graphic";
const IMAGE_VND_DJVU = "image/vnd.djvu";
const IMAGE_VND_DWG = "image/vnd.dwg";
const IMAGE_VND_DXF = "image/vnd.dxf";
const IMAGE_VND_FASTBIDSHEET = "image/vnd.fastbidsheet";
const IMAGE_VND_FPX = "image/vnd.fpx";
const IMAGE_VND_FST = "image/vnd.fst";
const IMAGE_VND_FUJIXEROX_EDMICS_MMR = "image/vnd.fujixerox.edmics-mmr";
const IMAGE_VND_FUJIXEROX_EDMICS_RLC = "image/vnd.fujixerox.edmics-rlc";
const IMAGE_VND_MS_DDS = "image/vnd.ms-dds";
const IMAGE_VND_MS_MODI = "image/vnd.ms-modi";
const IMAGE_VND_MS_PHOTO = "image/vnd.ms-photo";
const IMAGE_VND_NET_FPX = "image/vnd.net-fpx";
const IMAGE_VND_PCO_B16 = "image/vnd.pco.b16";
const IMAGE_VND_TENCENT_TAP = "image/vnd.tencent.tap";
const IMAGE_VND_VALVE_SOURCE_TEXTURE = "image/vnd.valve.source.texture";
const IMAGE_VND_WAP_WBMP = "image/vnd.wap.wbmp";
const IMAGE_VND_XIFF = "image/vnd.xiff";
const IMAGE_WEBP = "image/webp";
const IMAGE_WMF = "image/wmf";
const IMAGE_X_3DS = "image/x-3ds";
const IMAGE_X_CMU_RASTER = "image/x-cmu-raster";
const IMAGE_X_CMX = "image/x-cmx";
const IMAGE_X_FREEHAND = "image/x-freehand";
const IMAGE_X_ICON = "image/x-icon";
const IMAGE_X_JNG = "image/x-jng";
const IMAGE_X_MRSID_IMAGE = "image/x-mrsid-image";
const IMAGE_X_PCX = "image/x-pcx";
const IMAGE_X_PICT = "image/x-pict";
const IMAGE_X_PORTABLE_ANYMAP = "image/x-portable-anymap";
const IMAGE_X_PORTABLE_BITMAP = "image/x-portable-bitmap";
const IMAGE_X_PORTABLE_GRAYMAP = "image/x-portable-graymap";
const IMAGE_X_PORTABLE_PIXMAP = "image/x-portable-pixmap";
const IMAGE_X_RGB = "image/x-rgb";
const IMAGE_X_TGA = "image/x-tga";
const IMAGE_X_XBITMAP = "image/x-xbitmap";
const IMAGE_X_XPIXMAP = "image/x-xpixmap";
const IMAGE_X_XWINDOWDUMP = "image/x-xwindowdump";
const MESSAGE_DISPOSITION_NOTIFICATION = "message/disposition-notification";
const MESSAGE_GLOBAL = "message/global";
const MESSAGE_GLOBAL_DELIVERY_STATUS = "message/global-delivery-status";
const MESSAGE_GLOBAL_DISPOSITION_NOTIFICATION = "message/global-disposition-notification";
const MESSAGE_GLOBAL_HEADERS = "message/global-headers";
const MESSAGE_RFC822 = "message/rfc822";
const MESSAGE_VND_WFA_WSC = "message/vnd.wfa.wsc";
const MODEL_3MF = "model/3mf";
const MODEL_GLTF_JSON = "model/gltf+json";
const MODEL_GLTF_BINARY = "model/gltf-binary";
const MODEL_IGES = "model/iges";
const MODEL_JT = "model/jt";
const MODEL_MESH = "model/mesh";
const MODEL_MTL = "model/mtl";
const MODEL_OBJ = "model/obj";
const MODEL_PRC = "model/prc";
const MODEL_STEP_XML = "model/step+xml";
const MODEL_STEP_ZIP = "model/step+zip";
const MODEL_STEP_XML_ZIP = "model/step-xml+zip";
const MODEL_STL = "model/stl";
const MODEL_U3D = "model/u3d";
const MODEL_VND_CLD = "model/vnd.cld";
const MODEL_VND_COLLADA_XML = "model/vnd.collada+xml";
const MODEL_VND_DWF = "model/vnd.dwf";
const MODEL_VND_GDL = "model/vnd.gdl";
const MODEL_VND_GTW = "model/vnd.gtw";
const MODEL_VND_MTS = "model/vnd.mts";
const MODEL_VND_OPENGEX = "model/vnd.opengex";
const MODEL_VND_PARASOLID_TRANSMIT_BINARY = "model/vnd.parasolid.transmit.binary";
const MODEL_VND_PARASOLID_TRANSMIT_TEXT = "model/vnd.parasolid.transmit.text";
const MODEL_VND_PYTHA_PYOX = "model/vnd.pytha.pyox";
const MODEL_VND_SAP_VDS = "model/vnd.sap.vds";
const MODEL_VND_USDA = "model/vnd.usda";
const MODEL_VND_USDZ_ZIP = "model/vnd.usdz+zip";
const MODEL_VND_VALVE_SOURCE_COMPILED_MAP = "model/vnd.valve.source.compiled-map";
const MODEL_VND_VTU = "model/vnd.vtu";
const MODEL_VRML = "model/vrml";
const MODEL_X3D_BINARY = "model/x3d+binary";
const MODEL_X3D_FASTINFOSET = "model/x3d+fastinfoset";
const MODEL_X3D_VRML = "model/x3d+vrml";
const MODEL_X3D_XML = "model/x3d+xml";
const TEXT_CACHE_MANIFEST = "text/cache-manifest";
const TEXT_CALENDAR = "text/calendar";
const TEXT_COFFEESCRIPT = "text/coffeescript";
const TEXT_CSS = "text/css";
const TEXT_CSV = "text/csv";
const TEXT_HTML = "text/html";
const TEXT_JADE = "text/jade";
const TEXT_JAVASCRIPT = "text/javascript";
const TEXT_JSX = "text/jsx";
const TEXT_LESS = "text/less";
const TEXT_MARKDOWN = "text/markdown";
const TEXT_MATHML = "text/mathml";
const TEXT_MDX = "text/mdx";
const TEXT_N3 = "text/n3";
const TEXT_PLAIN = "text/plain";
const TEXT_PRS_LINES_TAG = "text/prs.lines.tag";
const TEXT_RICHTEXT = "text/richtext";
const TEXT_RTF = "text/rtf";
const TEXT_SGML = "text/sgml";
const TEXT_SHEX = "text/shex";
const TEXT_SLIM = "text/slim";
const TEXT_SPDX = "text/spdx";
const TEXT_STYLUS = "text/stylus";
const TEXT_TAB_SEPARATED_VALUES = "text/tab-separated-values";
const TEXT_TROFF = "text/troff";
const TEXT_TURTLE = "text/turtle";
const TEXT_URI_LIST = "text/uri-list";
const TEXT_VCARD = "text/vcard";
const TEXT_VND_CURL = "text/vnd.curl";
const TEXT_VND_CURL_DCURL = "text/vnd.curl.dcurl";
const TEXT_VND_CURL_MCURL = "text/vnd.curl.mcurl";
const TEXT_VND_CURL_SCURL = "text/vnd.curl.scurl";
const TEXT_VND_DVB_SUBTITLE = "text/vnd.dvb.subtitle";
const TEXT_VND_FAMILYSEARCH_GEDCOM = "text/vnd.familysearch.gedcom";
const TEXT_VND_FLY = "text/vnd.fly";
const TEXT_VND_FMI_FLEXSTOR = "text/vnd.fmi.flexstor";
const TEXT_VND_GRAPHVIZ = "text/vnd.graphviz";
const TEXT_VND_IN3D_3DML = "text/vnd.in3d.3dml";
const TEXT_VND_IN3D_SPOT = "text/vnd.in3d.spot";
const TEXT_VND_SUN_J2ME_APP_DESCRIPTOR = "text/vnd.sun.j2me.app-descriptor";
const TEXT_VND_WAP_WML = "text/vnd.wap.wml";
const TEXT_VND_WAP_WMLSCRIPT = "text/vnd.wap.wmlscript";
const TEXT_VTT = "text/vtt";
const TEXT_WGSL = "text/wgsl";
const TEXT_X_ASM = "text/x-asm";
const TEXT_X_C = "text/x-c";
const TEXT_X_COMPONENT = "text/x-component";
const TEXT_X_FORTRAN = "text/x-fortran";
const TEXT_X_HANDLEBARS_TEMPLATE = "text/x-handlebars-template";
const TEXT_X_JAVA_SOURCE = "text/x-java-source";
const TEXT_X_LUA = "text/x-lua";
const TEXT_X_MARKDOWN = "text/x-markdown";
const TEXT_X_NFO = "text/x-nfo";
const TEXT_X_OPML = "text/x-opml";
const TEXT_X_ORG = "text/x-org";
const TEXT_X_PASCAL = "text/x-pascal";
const TEXT_X_PROCESSING = "text/x-processing";
const TEXT_X_SASS = "text/x-sass";
const TEXT_X_SCRIPTZSH = "text/x-scriptzsh";
const TEXT_X_SCSS = "text/x-scss";
const TEXT_X_SETEXT = "text/x-setext";
const TEXT_X_SFV = "text/x-sfv";
const TEXT_X_SUSE_YMP = "text/x-suse-ymp";
const TEXT_X_UUENCODE = "text/x-uuencode";
const TEXT_X_VCALENDAR = "text/x-vcalendar";
const TEXT_X_VCARD = "text/x-vcard";
const TEXT_YAML = "text/yaml";
const VIDEO_3GP = "video/3gp";
const VIDEO_3GPP = "video/3gpp";
const VIDEO_3GPP2 = "video/3gpp2";
const VIDEO_H261 = "video/h261";
const VIDEO_H263 = "video/h263";
const VIDEO_H264 = "video/h264";
const VIDEO_ISO_SEGMENT = "video/iso.segment";
const VIDEO_JPEG = "video/jpeg";
const VIDEO_JPM = "video/jpm";
const VIDEO_MJ2 = "video/mj2";
const VIDEO_MP2T = "video/mp2t";
const VIDEO_MP4 = "video/mp4";
const VIDEO_MPEG = "video/mpeg";
const VIDEO_OGG = "video/ogg";
const VIDEO_QUICKTIME = "video/quicktime";
const VIDEO_VND_DECE_HD = "video/vnd.dece.hd";
const VIDEO_VND_DECE_MOBILE = "video/vnd.dece.mobile";
const VIDEO_VND_DECE_PD = "video/vnd.dece.pd";
const VIDEO_VND_DECE_SD = "video/vnd.dece.sd";
const VIDEO_VND_DECE_VIDEO = "video/vnd.dece.video";
const VIDEO_VND_DVB_FILE = "video/vnd.dvb.file";
const VIDEO_VND_FVT = "video/vnd.fvt";
const VIDEO_VND_MPEGURL = "video/vnd.mpegurl";
const VIDEO_VND_MS_PLAYREADY_MEDIA_PYV = "video/vnd.ms-playready.media.pyv";
const VIDEO_VND_RN_REALVIDEO = "video/vnd.rn-realvideo";
const VIDEO_VND_UVVU_MP4 = "video/vnd.uvvu.mp4";
const VIDEO_VND_VIVO = "video/vnd.vivo";
const VIDEO_WEBM = "video/webm";
const VIDEO_X_FLI = "video/x-fli";
const VIDEO_X_FLV = "video/x-flv";
const VIDEO_X_M4V = "video/x-m4v";
const VIDEO_X_MATROSKA = "video/x-matroska";
const VIDEO_X_MNG = "video/x-mng";
const VIDEO_X_MS_ASF = "video/x-ms-asf";
const VIDEO_X_MS_VOB = "video/x-ms-vob";
const VIDEO_X_MS_WM = "video/x-ms-wm";
const VIDEO_X_MS_WMV = "video/x-ms-wmv";
const VIDEO_X_MS_WMX = "video/x-ms-wmx";
const VIDEO_X_MS_WVX = "video/x-ms-wvx";
const VIDEO_X_MSVIDEO = "video/x-msvideo";
const VIDEO_X_SGI_MOVIE = "video/x-sgi-movie";
const VIDEO_X_SMV = "video/x-smv";
const X_CONFERENCE_X_COOLTALK = "x-conference/x-cooltalk";

MagicObject\Constants\PicoMimeMap

Declaration

class PicoMimeMap { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoMimeMap

This class defines a mapping of file extensions to their corresponding MIME types. It can be used to determine the appropriate content type for files based on their extensions.

Constants

const MIME_TYPES_FOR_EXTENSIONS = array (\n '1km' => 'application/vnd.1000minds.decision-model+xml',\n '3dml' => 'text/vnd.in3d.3dml',\n '3ds' => 'image/x-3ds',\n '3g2' => 'video/3gpp2',\n '3gp' => 'video/3gp',\n '3gpp' => 'video/3gpp',\n '3mf' => 'model/3mf',\n '7z' => 'application/x-7z-compressed',\n '7zip' => 'application/x-7z-compressed',\n 123 => 'application/vnd.lotus-1-2-3',\n 'aab' => 'application/x-authorware-bin',\n 'aac' => 'audio/acc',\n 'aam' => 'application/x-authorware-map',\n 'aas' => 'application/x-authorware-seg',\n 'abw' => 'application/x-abiword',\n 'ac' => 'application/vnd.nokia.n-gage.ac+xml',\n 'ac3' => 'audio/ac3',\n 'acc' => 'application/vnd.americandynamics.acc',\n 'ace' => 'application/x-ace-compressed',\n 'acu' => 'application/vnd.acucobol',\n 'acutc' => 'application/vnd.acucorp',\n 'adp' => 'audio/adpcm',\n 'adts' => 'audio/aac',\n 'aep' => 'application/vnd.audiograph',\n 'afm' => 'application/x-font-type1',\n 'afp' => 'application/vnd.ibm.modcap',\n 'age' => 'application/vnd.age',\n 'ahead' => 'application/vnd.ahead.space',\n 'ai' => 'application/pdf',\n 'aif' => 'audio/x-aiff',\n 'aifc' => 'audio/x-aiff',\n 'aiff' => 'audio/x-aiff',\n 'air' => 'application/vnd.adobe.air-application-installer-package+zip',\n 'ait' => 'application/vnd.dvb.ait',\n 'ami' => 'application/vnd.amiga.ami',\n 'aml' => 'application/automationml-aml+xml',\n 'amlx' => 'application/automationml-amlx+zip',\n 'amr' => 'audio/amr',\n 'apk' => 'application/vnd.android.package-archive',\n 'apng' => 'image/apng',\n 'appcache' => 'text/cache-manifest',\n 'appinstaller' => 'application/appinstaller',\n 'application' => 'application/x-ms-application',\n 'appx' => 'application/appx',\n 'appxbundle' => 'application/appxbundle',\n 'apr' => 'application/vnd.lotus-approach',\n 'arc' => 'application/x-freearc',\n 'arj' => 'application/x-arj',\n 'asc' => 'application/pgp-signature',\n 'asf' => 'video/x-ms-asf',\n 'asm' => 'text/x-asm',\n 'aso' => 'application/vnd.accpac.simply.aso',\n 'asx' => 'video/x-ms-asf',\n 'atc' => 'application/vnd.acucorp',\n 'atom' => 'application/atom+xml',\n 'atomcat' => 'application/atomcat+xml',\n 'atomdeleted' => 'application/atomdeleted+xml',\n 'atomsvc' => 'application/atomsvc+xml',\n 'atx' => 'application/vnd.antix.game-component',\n 'au' => 'audio/x-au',\n 'avci' => 'image/avci',\n 'avcs' => 'image/avcs',\n 'avi' => 'video/x-msvideo',\n 'avif' => 'image/avif',\n 'aw' => 'application/applixware',\n 'azf' => 'application/vnd.airzip.filesecure.azf',\n 'azs' => 'application/vnd.airzip.filesecure.azs',\n 'azv' => 'image/vnd.airzip.accelerator.azv',\n 'azw' => 'application/vnd.amazon.ebook',\n 'b16' => 'image/vnd.pco.b16',\n 'bat' => 'application/x-msdownload',\n 'bcpio' => 'application/x-bcpio',\n 'bdf' => 'application/x-font-bdf',\n 'bdm' => 'application/vnd.syncml.dm+wbxml',\n 'bdoc' => 'application/x-bdoc',\n 'bed' => 'application/vnd.realvnc.bed',\n 'bh2' => 'application/vnd.fujitsu.oasysprs',\n 'bin' => 'application/octet-stream',\n 'blb' => 'application/x-blorb',\n 'blorb' => 'application/x-blorb',\n 'bmi' => 'application/vnd.bmi',\n 'bmml' => 'application/vnd.balsamiq.bmml+xml',\n 'bmp' => 'image/bmp',\n 'book' => 'application/vnd.framemaker',\n 'box' => 'application/vnd.previewsystems.box',\n 'boz' => 'application/x-bzip2',\n 'bpk' => 'application/octet-stream',\n 'bpmn' => 'application/octet-stream',\n 'brf' => 'application/braille',\n 'bsp' => 'model/vnd.valve.source.compiled-map',\n 'btf' => 'image/prs.btif',\n 'btif' => 'image/prs.btif',\n 'buffer' => 'application/octet-stream',\n 'bz' => 'application/x-bzip',\n 'bz2' => 'application/x-bzip2',\n 'c' => 'text/x-c',\n 'c4d' => 'application/vnd.clonk.c4group',\n 'c4f' => 'application/vnd.clonk.c4group',\n 'c4g' => 'application/vnd.clonk.c4group',\n 'c4p' => 'application/vnd.clonk.c4group',\n 'c4u' => 'application/vnd.clonk.c4group',\n 'c11amc' => 'application/vnd.cluetrust.cartomobile-config',\n 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg',\n 'cab' => 'application/vnd.ms-cab-compressed',\n 'caf' => 'audio/x-caf',\n 'cap' => 'application/vnd.tcpdump.pcap',\n 'car' => 'application/vnd.curl.car',\n 'cat' => 'application/vnd.ms-pki.seccat',\n 'cb7' => 'application/x-cbr',\n 'cba' => 'application/x-cbr',\n 'cbr' => 'application/x-cbr',\n 'cbt' => 'application/x-cbr',\n 'cbz' => 'application/x-cbr',\n 'cc' => 'text/x-c',\n 'cco' => 'application/x-cocoa',\n 'cct' => 'application/x-director',\n 'ccxml' => 'application/ccxml+xml',\n 'cdbcmsg' => 'application/vnd.contact.cmsg',\n 'cdf' => 'application/x-netcdf',\n 'cdfx' => 'application/cdfx+xml',\n 'cdkey' => 'application/vnd.mediastation.cdkey',\n 'cdmia' => 'application/cdmi-capability',\n 'cdmic' => 'application/cdmi-container',\n 'cdmid' => 'application/cdmi-domain',\n 'cdmio' => 'application/cdmi-object',\n 'cdmiq' => 'application/cdmi-queue',\n 'cdr' => 'application/cdr',\n 'cdx' => 'chemical/x-cdx',\n 'cdxml' => 'application/vnd.chemdraw+xml',\n 'cdy' => 'application/vnd.cinderella',\n 'cer' => 'application/pkix-cert',\n 'cfs' => 'application/x-cfs-compressed',\n 'cgm' => 'image/cgm',\n 'chat' => 'application/x-chat',\n 'chm' => 'application/vnd.ms-htmlhelp',\n 'chrt' => 'application/vnd.kde.kchart',\n 'cif' => 'chemical/x-cif',\n 'cii' => 'application/vnd.anser-web-certificate-issue-initiation',\n 'cil' => 'application/vnd.ms-artgalry',\n 'cjs' => 'application/node',\n 'cla' => 'application/vnd.claymore',\n 'class' => 'application/octet-stream',\n 'cld' => 'model/vnd.cld',\n 'clkk' => 'application/vnd.crick.clicker.keyboard',\n 'clkp' => 'application/vnd.crick.clicker.palette',\n 'clkt' => 'application/vnd.crick.clicker.template',\n 'clkw' => 'application/vnd.crick.clicker.wordbank',\n 'clkx' => 'application/vnd.crick.clicker',\n 'clp' => 'application/x-msclip',\n 'cmc' => 'application/vnd.cosmocaller',\n 'cmdf' => 'chemical/x-cmdf',\n 'cml' => 'chemical/x-cml',\n 'cmp' => 'application/vnd.yellowriver-custom-menu',\n 'cmx' => 'image/x-cmx',\n 'cod' => 'application/vnd.rim.cod',\n 'coffee' => 'text/coffeescript',\n 'com' => 'application/x-msdownload',\n 'conf' => 'text/plain',\n 'cpio' => 'application/x-cpio',\n 'cpl' => 'application/cpl+xml',\n 'cpp' => 'text/x-c',\n 'cpt' => 'application/mac-compactpro',\n 'crd' => 'application/x-mscardfile',\n 'crl' => 'application/pkix-crl',\n 'crt' => 'application/x-x509-ca-cert',\n 'crx' => 'application/x-chrome-extension',\n 'cryptonote' => 'application/vnd.rig.cryptonote',\n 'csh' => 'application/x-csh',\n 'csl' => 'application/vnd.citationstyles.style+xml',\n 'csml' => 'chemical/x-csml',\n 'csp' => 'application/vnd.commonspace',\n 'csr' => 'application/octet-stream',\n 'css' => 'text/css',\n 'cst' => 'application/x-director',\n 'csv' => 'text/csv',\n 'cu' => 'application/cu-seeme',\n 'curl' => 'text/vnd.curl',\n 'cwl' => 'application/cwl',\n 'cww' => 'application/prs.cww',\n 'cxt' => 'application/x-director',\n 'cxx' => 'text/x-c',\n 'dae' => 'model/vnd.collada+xml',\n 'daf' => 'application/vnd.mobius.daf',\n 'dart' => 'application/vnd.dart',\n 'dataless' => 'application/vnd.fdsn.seed',\n 'davmount' => 'application/davmount+xml',\n 'dbf' => 'application/vnd.dbf',\n 'dbk' => 'application/docbook+xml',\n 'dcr' => 'application/x-director',\n 'dcurl' => 'text/vnd.curl.dcurl',\n 'dd2' => 'application/vnd.oma.dd2+xml',\n 'ddd' => 'application/vnd.fujixerox.ddd',\n 'ddf' => 'application/vnd.syncml.dmddf+xml',\n 'dds' => 'image/vnd.ms-dds',\n 'deb' => 'application/x-debian-package',\n 'def' => 'text/plain',\n 'deploy' => 'application/octet-stream',\n 'der' => 'application/x-x509-ca-cert',\n 'dfac' => 'application/vnd.dreamfactory',\n 'dgc' => 'application/x-dgc-compressed',\n 'dib' => 'image/bmp',\n 'dic' => 'text/x-c',\n 'dir' => 'application/x-director',\n 'dis' => 'application/vnd.mobius.dis',\n 'disposition-notification' => 'message/disposition-notification',\n 'dist' => 'application/octet-stream',\n 'distz' => 'application/octet-stream',\n 'djv' => 'image/vnd.djvu',\n 'djvu' => 'image/vnd.djvu',\n 'dll' => 'application/octet-stream',\n 'dmg' => 'application/x-apple-diskimage',\n 'dmn' => 'application/octet-stream',\n 'dmp' => 'application/vnd.tcpdump.pcap',\n 'dms' => 'application/octet-stream',\n 'dna' => 'application/vnd.dna',\n 'doc' => 'application/msword',\n 'docm' => 'application/vnd.ms-word.template.macroEnabled.12',\n 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'dot' => 'application/msword',\n 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',\n 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',\n 'dp' => 'application/vnd.osgi.dp',\n 'dpg' => 'application/vnd.dpgraph',\n 'dpx' => 'image/dpx',\n 'dra' => 'audio/vnd.dra',\n 'drle' => 'image/dicom-rle',\n 'dsc' => 'text/prs.lines.tag',\n 'dssc' => 'application/dssc+der',\n 'dst' => 'application/octet-stream',\n 'dtb' => 'application/x-dtbook+xml',\n 'dtd' => 'application/xml-dtd',\n 'dts' => 'audio/vnd.dts',\n 'dtshd' => 'audio/vnd.dts.hd',\n 'dump' => 'application/octet-stream',\n 'dvb' => 'video/vnd.dvb.file',\n 'dvi' => 'application/x-dvi',\n 'dwd' => 'application/atsc-dwd+xml',\n 'dwf' => 'model/vnd.dwf',\n 'dwg' => 'image/vnd.dwg',\n 'dxf' => 'image/vnd.dxf',\n 'dxp' => 'application/vnd.spotfire.dxp',\n 'dxr' => 'application/x-director',\n 'ear' => 'application/java-archive',\n 'ecelp4800' => 'audio/vnd.nuera.ecelp4800',\n 'ecelp7470' => 'audio/vnd.nuera.ecelp7470',\n 'ecelp9600' => 'audio/vnd.nuera.ecelp9600',\n 'ecma' => 'application/ecmascript',\n 'edm' => 'application/vnd.novadigm.edm',\n 'edx' => 'application/vnd.novadigm.edx',\n 'efif' => 'application/vnd.picsel',\n 'ei6' => 'application/vnd.pg.osasli',\n 'elc' => 'application/octet-stream',\n 'emf' => 'image/emf',\n 'eml' => 'message/rfc822',\n 'emma' => 'application/emma+xml',\n 'emotionml' => 'application/emotionml+xml',\n 'emz' => 'application/x-msmetafile',\n 'eol' => 'audio/vnd.digital-winds',\n 'eot' => 'application/vnd.ms-fontobject',\n 'eps' => 'application/postscript',\n 'epub' => 'application/epub+zip',\n 'es3' => 'application/vnd.eszigno3+xml',\n 'esa' => 'application/vnd.osgi.subsystem',\n 'esf' => 'application/vnd.epson.esf',\n 'et3' => 'application/vnd.eszigno3+xml',\n 'etx' => 'text/x-setext',\n 'eva' => 'application/x-eva',\n 'evy' => 'application/x-envoy',\n 'exe' => 'application/octet-stream',\n 'exi' => 'application/exi',\n 'exp' => 'application/express',\n 'exr' => 'image/aces',\n 'ext' => 'application/vnd.novadigm.ext',\n 'ez' => 'application/andrew-inset',\n 'ez2' => 'application/vnd.ezpix-album',\n 'ez3' => 'application/vnd.ezpix-package',\n 'f' => 'text/x-fortran',\n 'f4v' => 'video/mp4',\n 'f77' => 'text/x-fortran',\n 'f90' => 'text/x-fortran',\n 'fbs' => 'image/vnd.fastbidsheet',\n 'fcdt' => 'application/vnd.adobe.formscentral.fcdt',\n 'fcs' => 'application/vnd.isac.fcs',\n 'fdf' => 'application/vnd.fdf',\n 'fdt' => 'application/fdt+xml',\n 'fe_launch' => 'application/vnd.denovo.fcselayout-link',\n 'fg5' => 'application/vnd.fujitsu.oasysgp',\n 'fgd' => 'application/x-director',\n 'fh' => 'image/x-freehand',\n 'fh4' => 'image/x-freehand',\n 'fh5' => 'image/x-freehand',\n 'fh7' => 'image/x-freehand',\n 'fhc' => 'image/x-freehand',\n 'fig' => 'application/x-xfig',\n 'fits' => 'image/fits',\n 'flac' => 'audio/x-flac',\n 'fli' => 'video/x-fli',\n 'flo' => 'application/vnd.micrografx.flo',\n 'flv' => 'video/x-flv',\n 'flw' => 'application/vnd.kde.kivio',\n 'flx' => 'text/vnd.fmi.flexstor',\n 'fly' => 'text/vnd.fly',\n 'fm' => 'application/vnd.framemaker',\n 'fnc' => 'application/vnd.frogans.fnc',\n 'fo' => 'application/vnd.software602.filler.form+xml',\n 'for' => 'text/x-fortran',\n 'fpx' => 'image/vnd.fpx',\n 'frame' => 'application/vnd.framemaker',\n 'fsc' => 'application/vnd.fsc.weblaunch',\n 'fst' => 'image/vnd.fst',\n 'ftc' => 'application/vnd.fluxtime.clip',\n 'fti' => 'application/vnd.anser-web-funds-transfer-initiation',\n 'fvt' => 'video/vnd.fvt',\n 'fxp' => 'application/vnd.adobe.fxp',\n 'fxpl' => 'application/vnd.adobe.fxp',\n 'fzs' => 'application/vnd.fuzzysheet',\n 'g2w' => 'application/vnd.geoplan',\n 'g3' => 'image/g3fax',\n 'g3w' => 'application/vnd.geospace',\n 'gac' => 'application/vnd.groove-account',\n 'gam' => 'application/x-tads',\n 'gbr' => 'application/rpki-ghostbusters',\n 'gca' => 'application/x-gca-compressed',\n 'gdl' => 'model/vnd.gdl',\n 'gdoc' => 'application/vnd.google-apps.document',\n 'ged' => 'text/vnd.familysearch.gedcom',\n 'geo' => 'application/vnd.dynageo',\n 'geojson' => 'application/geo+json',\n 'gex' => 'application/vnd.geometry-explorer',\n 'ggb' => 'application/vnd.geogebra.file',\n 'ggt' => 'application/vnd.geogebra.tool',\n 'ghf' => 'application/vnd.groove-help',\n 'gif' => 'image/gif',\n 'gim' => 'application/vnd.groove-identity-message',\n 'glb' => 'model/gltf-binary',\n 'gltf' => 'model/gltf+json',\n 'gml' => 'application/gml+xml',\n 'gmx' => 'application/vnd.gmx',\n 'gnumeric' => 'application/x-gnumeric',\n 'gpg' => 'application/gpg-keys',\n 'gph' => 'application/vnd.flographit',\n 'gpx' => 'application/gpx+xml',\n 'gqf' => 'application/vnd.grafeq',\n 'gqs' => 'application/vnd.grafeq',\n 'gram' => 'application/srgs',\n 'gramps' => 'application/x-gramps-xml',\n 'gre' => 'application/vnd.geometry-explorer',\n 'grv' => 'application/vnd.groove-injector',\n 'grxml' => 'application/srgs+xml',\n 'gsf' => 'application/x-font-ghostscript',\n 'gsheet' => 'application/vnd.google-apps.spreadsheet',\n 'gslides' => 'application/vnd.google-apps.presentation',\n 'gtar' => 'application/x-gtar',\n 'gtm' => 'application/vnd.groove-tool-message',\n 'gtw' => 'model/vnd.gtw',\n 'gv' => 'text/vnd.graphviz',\n 'gxf' => 'application/gxf',\n 'gxt' => 'application/vnd.geonext',\n 'gz' => 'application/gzip',\n 'gzip' => 'application/gzip',\n 'h' => 'text/x-c',\n 'h261' => 'video/h261',\n 'h263' => 'video/h263',\n 'h264' => 'video/h264',\n 'hal' => 'application/vnd.hal+xml',\n 'hbci' => 'application/vnd.hbci',\n 'hbs' => 'text/x-handlebars-template',\n 'hdd' => 'application/x-virtualbox-hdd',\n 'hdf' => 'application/x-hdf',\n 'heic' => 'image/heic',\n 'heics' => 'image/heic-sequence',\n 'heif' => 'image/heif',\n 'heifs' => 'image/heif-sequence',\n 'hej2' => 'image/hej2k',\n 'held' => 'application/atsc-held+xml',\n 'hh' => 'text/x-c',\n 'hjson' => 'application/hjson',\n 'hlp' => 'application/winhlp',\n 'hpgl' => 'application/vnd.hp-hpgl',\n 'hpid' => 'application/vnd.hp-hpid',\n 'hps' => 'application/vnd.hp-hps',\n 'hqx' => 'application/mac-binhex40',\n 'hsj2' => 'image/hsj2',\n 'htc' => 'text/x-component',\n 'htke' => 'application/vnd.kenameaapp',\n 'htm' => 'text/html',\n 'html' => 'text/html',\n 'hvd' => 'application/vnd.yamaha.hv-dic',\n 'hvp' => 'application/vnd.yamaha.hv-voice',\n 'hvs' => 'application/vnd.yamaha.hv-script',\n 'i2g' => 'application/vnd.intergeo',\n 'icc' => 'application/vnd.iccprofile',\n 'ice' => 'x-conference/x-cooltalk',\n 'icm' => 'application/vnd.iccprofile',\n 'ico' => 'image/x-icon',\n 'ics' => 'text/calendar',\n 'ief' => 'image/ief',\n 'ifb' => 'text/calendar',\n 'ifm' => 'application/vnd.shana.informed.formdata',\n 'iges' => 'model/iges',\n 'igl' => 'application/vnd.igloader',\n 'igm' => 'application/vnd.insors.igm',\n 'igs' => 'model/iges',\n 'igx' => 'application/vnd.micrografx.igx',\n 'iif' => 'application/vnd.shana.informed.interchange',\n 'img' => 'application/octet-stream',\n 'imp' => 'application/vnd.accpac.simply.imp',\n 'ims' => 'application/vnd.ms-ims',\n 'in' => 'text/plain',\n 'ini' => 'text/plain',\n 'ink' => 'application/inkml+xml',\n 'inkml' => 'application/inkml+xml',\n 'install' => 'application/x-install-instructions',\n 'iota' => 'application/vnd.astraea-software.iota',\n 'ipfix' => 'application/ipfix',\n 'ipk' => 'application/vnd.shana.informed.package',\n 'irm' => 'application/vnd.ibm.rights-management',\n 'irp' => 'application/vnd.irepository.package+xml',\n 'iso' => 'application/x-iso9660-image',\n 'itp' => 'application/vnd.shana.informed.formtemplate',\n 'its' => 'application/its+xml',\n 'ivp' => 'application/vnd.immervision-ivp',\n 'ivu' => 'application/vnd.immervision-ivu',\n 'jad' => 'text/vnd.sun.j2me.app-descriptor',\n 'jade' => 'text/jade',\n 'jam' => 'application/vnd.jam',\n 'jar' => 'application/java-archive',\n 'jardiff' => 'application/x-java-archive-diff',\n 'java' => 'text/x-java-source',\n 'jhc' => 'image/jphc',\n 'jisp' => 'application/vnd.jisp',\n 'jls' => 'image/jls',\n 'jlt' => 'application/vnd.hp-jlyt',\n 'jng' => 'image/x-jng',\n 'jnlp' => 'application/x-java-jnlp-file',\n 'joda' => 'application/vnd.joost.joda-archive',\n 'jp2' => 'image/jp2',\n 'jpe' => 'image/jpeg',\n 'jpeg' => 'image/jpeg',\n 'jpf' => 'image/jpx',\n 'jpg' => 'image/jpeg',\n 'jpg2' => 'image/jp2',\n 'jpgm' => 'video/jpm',\n 'jpgv' => 'video/jpeg',\n 'jph' => 'image/jph',\n 'jpm' => 'video/jpm',\n 'jpx' => 'image/jpx',\n 'js' => 'application/javascript',\n 'json' => 'application/json',\n 'json5' => 'application/json5',\n 'jsonld' => 'application/ld+json',\n 'jsonml' => 'application/jsonml+json',\n 'jsx' => 'text/jsx',\n 'jt' => 'model/jt',\n 'jxr' => 'image/jxr',\n 'jxra' => 'image/jxra',\n 'jxrs' => 'image/jxrs',\n 'jxs' => 'image/jxs',\n 'jxsc' => 'image/jxsc',\n 'jxsi' => 'image/jxsi',\n 'jxss' => 'image/jxss',\n 'kar' => 'audio/midi',\n 'karbon' => 'application/vnd.kde.karbon',\n 'kdb' => 'application/octet-stream',\n 'kdbx' => 'application/x-keepass2',\n 'key' => 'application/x-iwork-keynote-sffkey',\n 'kfo' => 'application/vnd.kde.kformula',\n 'kia' => 'application/vnd.kidspiration',\n 'kml' => 'application/vnd.google-earth.kml+xml',\n 'kmz' => 'application/vnd.google-earth.kmz',\n 'kne' => 'application/vnd.kinar',\n 'knp' => 'application/vnd.kinar',\n 'kon' => 'application/vnd.kde.kontour',\n 'kpr' => 'application/vnd.kde.kpresenter',\n 'kpt' => 'application/vnd.kde.kpresenter',\n 'kpxx' => 'application/vnd.ds-keypoint',\n 'ksp' => 'application/vnd.kde.kspread',\n 'ktr' => 'application/vnd.kahootz',\n 'ktx' => 'image/ktx',\n 'ktx2' => 'image/ktx2',\n 'ktz' => 'application/vnd.kahootz',\n 'kwd' => 'application/vnd.kde.kword',\n 'kwt' => 'application/vnd.kde.kword',\n 'lasxml' => 'application/vnd.las.las+xml',\n 'latex' => 'application/x-latex',\n 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop',\n 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml',\n 'les' => 'application/vnd.hhe.lesson-player',\n 'less' => 'text/less',\n 'lgr' => 'application/lgr+xml',\n 'lha' => 'application/octet-stream',\n 'link66' => 'application/vnd.route66.link66+xml',\n 'list' => 'text/plain',\n 'list3820' => 'application/vnd.ibm.modcap',\n 'listafp' => 'application/vnd.ibm.modcap',\n 'litcoffee' => 'text/coffeescript',\n 'lnk' => 'application/x-ms-shortcut',\n 'log' => 'text/plain',\n 'lostxml' => 'application/lost+xml',\n 'lrf' => 'application/octet-stream',\n 'lrm' => 'application/vnd.ms-lrm',\n 'ltf' => 'application/vnd.frogans.ltf',\n 'lua' => 'text/x-lua',\n 'luac' => 'application/x-lua-bytecode',\n 'lvp' => 'audio/vnd.lucent.voice',\n 'lwp' => 'application/vnd.lotus-wordpro',\n 'lzh' => 'application/octet-stream',\n 'm1v' => 'video/mpeg',\n 'm2a' => 'audio/mpeg',\n 'm2v' => 'video/mpeg',\n 'm3a' => 'audio/mpeg',\n 'm3u' => 'text/plain',\n 'm3u8' => 'application/vnd.apple.mpegurl',\n 'm4a' => 'audio/x-m4a',\n 'm4p' => 'application/mp4',\n 'm4s' => 'video/iso.segment',\n 'm4u' => 'application/vnd.mpegurl',\n 'm4v' => 'video/x-m4v',\n 'm13' => 'application/x-msmediaview',\n 'm14' => 'application/x-msmediaview',\n 'm21' => 'application/mp21',\n 'ma' => 'application/mathematica',\n 'mads' => 'application/mads+xml',\n 'maei' => 'application/mmt-aei+xml',\n 'mag' => 'application/vnd.ecowin.chart',\n 'maker' => 'application/vnd.framemaker',\n 'man' => 'text/troff',\n 'manifest' => 'text/cache-manifest',\n 'map' => 'application/json',\n 'mar' => 'application/octet-stream',\n 'markdown' => 'text/markdown',\n 'mathml' => 'application/mathml+xml',\n 'mb' => 'application/mathematica',\n 'mbk' => 'application/vnd.mobius.mbk',\n 'mbox' => 'application/mbox',\n 'mc1' => 'application/vnd.medcalcdata',\n 'mcd' => 'application/vnd.mcd',\n 'mcurl' => 'text/vnd.curl.mcurl',\n 'md' => 'text/markdown',\n 'mdb' => 'application/x-msaccess',\n 'mdi' => 'image/vnd.ms-modi',\n 'mdx' => 'text/mdx',\n 'me' => 'text/troff',\n 'mesh' => 'model/mesh',\n 'meta4' => 'application/metalink4+xml',\n 'metalink' => 'application/metalink+xml',\n 'mets' => 'application/mets+xml',\n 'mfm' => 'application/vnd.mfmp',\n 'mft' => 'application/rpki-manifest',\n 'mgp' => 'application/vnd.osgeo.mapguide.package',\n 'mgz' => 'application/vnd.proteus.magazine',\n 'mid' => 'audio/midi',\n 'midi' => 'audio/midi',\n 'mie' => 'application/x-mie',\n 'mif' => 'application/vnd.mif',\n 'mime' => 'message/rfc822',\n 'mj2' => 'video/mj2',\n 'mjp2' => 'video/mj2',\n 'mjs' => 'text/javascript',\n 'mk3d' => 'video/x-matroska',\n 'mka' => 'audio/x-matroska',\n 'mkd' => 'text/x-markdown',\n 'mks' => 'video/x-matroska',\n 'mkv' => 'video/x-matroska',\n 'mlp' => 'application/vnd.dolby.mlp',\n 'mmd' => 'application/vnd.chipnuts.karaoke-mmd',\n 'mmf' => 'application/vnd.smaf',\n 'mml' => 'text/mathml',\n 'mmr' => 'image/vnd.fujixerox.edmics-mmr',\n 'mng' => 'video/x-mng',\n 'mny' => 'application/x-msmoney',\n 'mobi' => 'application/x-mobipocket-ebook',\n 'mods' => 'application/mods+xml',\n 'mov' => 'video/quicktime',\n 'movie' => 'video/x-sgi-movie',\n 'mp2' => 'audio/mpeg',\n 'mp2a' => 'audio/mpeg',\n 'mp3' => 'audio/mpeg',\n 'mp4' => 'video/mp4',\n 'mp4a' => 'audio/mp4',\n 'mp4s' => 'application/mp4',\n 'mp4v' => 'video/mp4',\n 'mp21' => 'application/mp21',\n 'mpc' => 'application/vnd.mophun.certificate',\n 'mpd' => 'application/dash+xml',\n 'mpe' => 'video/mpeg',\n 'mpeg' => 'video/mpeg',\n 'mpf' => 'application/media-policy-dataset+xml',\n 'mpg' => 'video/mpeg',\n 'mpg4' => 'video/mp4',\n 'mpga' => 'audio/mpeg',\n 'mpkg' => 'application/vnd.apple.installer+xml',\n 'mpm' => 'application/vnd.blueice.multipass',\n 'mpn' => 'application/vnd.mophun.application',\n 'mpp' => 'application/vnd.ms-project',\n 'mpt' => 'application/vnd.ms-project',\n 'mpy' => 'application/vnd.ibm.minipay',\n 'mqy' => 'application/vnd.mobius.mqy',\n 'mrc' => 'application/marc',\n 'mrcx' => 'application/marcxml+xml',\n 'ms' => 'text/troff',\n 'mscml' => 'application/mediaservercontrol+xml',\n 'mseed' => 'application/vnd.fdsn.mseed',\n 'mseq' => 'application/vnd.mseq',\n 'msf' => 'application/vnd.epson.msf',\n 'msg' => 'application/vnd.ms-outlook',\n 'msh' => 'model/mesh',\n 'msi' => 'application/x-msdownload',\n 'msix' => 'application/msix',\n 'msixbundle' => 'application/msixbundle',\n 'msl' => 'application/vnd.mobius.msl',\n 'msm' => 'application/octet-stream',\n 'msp' => 'application/octet-stream',\n 'msty' => 'application/vnd.muvee.style',\n 'mtl' => 'model/mtl',\n 'mts' => 'model/vnd.mts',\n 'mus' => 'application/vnd.musician',\n 'musd' => 'application/mmt-usd+xml',\n 'musicxml' => 'application/vnd.recordare.musicxml+xml',\n 'mvb' => 'application/x-msmediaview',\n 'mvt' => 'application/vnd.mapbox-vector-tile',\n 'mwf' => 'application/vnd.mfer',\n 'mxf' => 'application/mxf',\n 'mxl' => 'application/vnd.recordare.musicxml',\n 'mxmf' => 'audio/mobile-xmf',\n 'mxml' => 'application/xv+xml',\n 'mxs' => 'application/vnd.triscape.mxs',\n 'mxu' => 'video/vnd.mpegurl',\n 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install',\n 'n3' => 'text/n3',\n 'nb' => 'application/mathematica',\n 'nbp' => 'application/vnd.wolfram.player',\n 'nc' => 'application/x-netcdf',\n 'ncx' => 'application/x-dtbncx+xml',\n 'ndjson' => 'application/x-ndjson',\n 'nfo' => 'text/x-nfo',\n 'ngdat' => 'application/vnd.nokia.n-gage.data',\n 'nitf' => 'application/vnd.nitf',\n 'nlu' => 'application/vnd.neurolanguage.nlu',\n 'nml' => 'application/vnd.enliven',\n 'nnd' => 'application/vnd.noblenet-directory',\n 'nns' => 'application/vnd.noblenet-sealer',\n 'nnw' => 'application/vnd.noblenet-web',\n 'npx' => 'image/vnd.net-fpx',\n 'nq' => 'application/n-quads',\n 'nsc' => 'application/x-conference',\n 'nsf' => 'application/vnd.lotus-notes',\n 'nt' => 'application/n-triples',\n 'ntf' => 'application/vnd.nitf',\n 'numbers' => 'application/x-iwork-numbers-sffnumbers',\n 'nzb' => 'application/x-nzb',\n 'oa2' => 'application/vnd.fujitsu.oasys2',\n 'oa3' => 'application/vnd.fujitsu.oasys3',\n 'oas' => 'application/vnd.fujitsu.oasys',\n 'obd' => 'application/x-msbinder',\n 'obgx' => 'application/vnd.openblox.game+xml',\n 'obj' => 'model/obj',\n 'oda' => 'application/oda',\n 'odb' => 'application/vnd.oasis.opendocument.database',\n 'odc' => 'application/vnd.oasis.opendocument.chart',\n 'odf' => 'application/vnd.oasis.opendocument.formula',\n 'odft' => 'application/vnd.oasis.opendocument.formula-template',\n 'odg' => 'application/vnd.oasis.opendocument.graphics',\n 'odi' => 'application/vnd.oasis.opendocument.image',\n 'odm' => 'application/vnd.oasis.opendocument.text-master',\n 'odp' => 'application/vnd.oasis.opendocument.presentation',\n 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',\n 'odt' => 'application/vnd.oasis.opendocument.text',\n 'oga' => 'audio/ogg',\n 'ogex' => 'model/vnd.opengex',\n 'ogg' => 'audio/ogg',\n 'ogv' => 'video/ogg',\n 'ogx' => 'application/ogg',\n 'omdoc' => 'application/omdoc+xml',\n 'onepkg' => 'application/onenote',\n 'onetmp' => 'application/onenote',\n 'onetoc' => 'application/onenote',\n 'onetoc2' => 'application/onenote',\n 'opf' => 'application/oebps-package+xml',\n 'opml' => 'text/x-opml',\n 'oprc' => 'application/vnd.palm',\n 'opus' => 'audio/ogg',\n 'org' => 'text/x-org',\n 'osf' => 'application/vnd.yamaha.openscoreformat',\n 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml',\n 'osm' => 'application/vnd.openstreetmap.data+xml',\n 'otc' => 'application/vnd.oasis.opendocument.chart-template',\n 'otf' => 'font/otf',\n 'otg' => 'application/vnd.oasis.opendocument.graphics-template',\n 'oth' => 'application/vnd.oasis.opendocument.text-web',\n 'oti' => 'application/vnd.oasis.opendocument.image-template',\n 'otp' => 'application/vnd.oasis.opendocument.presentation-template',\n 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',\n 'ott' => 'application/vnd.oasis.opendocument.text-template',\n 'ova' => 'application/x-virtualbox-ova',\n 'ovf' => 'application/x-virtualbox-ovf',\n 'owl' => 'application/rdf+xml',\n 'oxps' => 'application/oxps',\n 'oxt' => 'application/vnd.openofficeorg.extension',\n 'p' => 'text/x-pascal',\n 'p7a' => 'application/x-pkcs7-signature',\n 'p7b' => 'application/x-pkcs7-certificates',\n 'p7c' => 'application/pkcs7-mime',\n 'p7m' => 'application/pkcs7-mime',\n 'p7r' => 'application/x-pkcs7-certreqresp',\n 'p7s' => 'application/pkcs7-signature',\n 'p8' => 'application/pkcs8',\n 'p10' => 'application/x-pkcs10',\n 'p12' => 'application/x-pkcs12',\n 'pac' => 'application/x-ns-proxy-autoconfig',\n 'pages' => 'application/x-iwork-pages-sffpages',\n 'pas' => 'text/x-pascal',\n 'paw' => 'application/vnd.pawaafile',\n 'pbd' => 'application/vnd.powerbuilder6',\n 'pbm' => 'image/x-portable-bitmap',\n 'pcap' => 'application/vnd.tcpdump.pcap',\n 'pcf' => 'application/x-font-pcf',\n 'pcl' => 'application/vnd.hp-pcl',\n 'pclxl' => 'application/vnd.hp-pclxl',\n 'pct' => 'image/x-pict',\n 'pcurl' => 'application/vnd.curl.pcurl',\n 'pcx' => 'image/x-pcx',\n 'pdb' => 'application/x-pilot',\n 'pde' => 'text/x-processing',\n 'pdf' => 'application/pdf',\n 'pem' => 'application/x-x509-user-cert',\n 'pfa' => 'application/x-font-type1',\n 'pfb' => 'application/x-font-type1',\n 'pfm' => 'application/x-font-type1',\n 'pfr' => 'application/font-tdpfr',\n 'pfx' => 'application/x-pkcs12',\n 'pgm' => 'image/x-portable-graymap',\n 'pgn' => 'application/x-chess-pgn',\n 'pgp' => 'application/pgp',\n 'phar' => 'application/octet-stream',\n 'php' => 'application/x-httpd-php',\n 'php3' => 'application/x-httpd-php',\n 'php4' => 'application/x-httpd-php',\n 'phps' => 'application/x-httpd-php-source',\n 'phtml' => 'application/x-httpd-php',\n 'pic' => 'image/x-pict',\n 'pkg' => 'application/octet-stream',\n 'pki' => 'application/pkixcmp',\n 'pkipath' => 'application/pkix-pkipath',\n 'pkpass' => 'application/vnd.apple.pkpass',\n 'pl' => 'application/x-perl',\n 'plb' => 'application/vnd.3gpp.pic-bw-large',\n 'plc' => 'application/vnd.mobius.plc',\n 'plf' => 'application/vnd.pocketlearn',\n 'pls' => 'application/pls+xml',\n 'pm' => 'application/x-perl',\n 'pml' => 'application/vnd.ctc-posml',\n 'png' => 'image/png',\n 'pnm' => 'image/x-portable-anymap',\n 'portpkg' => 'application/vnd.macports.portpkg',\n 'pot' => 'application/vnd.ms-powerpoint',\n 'potm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',\n 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',\n 'ppa' => 'application/vnd.ms-powerpoint',\n 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',\n 'ppd' => 'application/vnd.cups-ppd',\n 'ppm' => 'image/x-portable-pixmap',\n 'pps' => 'application/vnd.ms-powerpoint',\n 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',\n 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',\n 'ppt' => 'application/powerpoint',\n 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',\n 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'pqa' => 'application/vnd.palm',\n 'prc' => 'model/prc',\n 'pre' => 'application/vnd.lotus-freelance',\n 'prf' => 'application/pics-rules',\n 'provx' => 'application/provenance+xml',\n 'ps' => 'application/postscript',\n 'psb' => 'application/vnd.3gpp.pic-bw-small',\n 'psd' => 'application/x-photoshop',\n 'psf' => 'application/x-font-linux-psf',\n 'pskcxml' => 'application/pskc+xml',\n 'pti' => 'image/prs.pti',\n 'ptid' => 'application/vnd.pvi.ptid1',\n 'pub' => 'application/x-mspublisher',\n 'pv' => 'application/octet-stream',\n 'pvb' => 'application/vnd.3gpp.pic-bw-var',\n 'pwn' => 'application/vnd.3m.post-it-notes',\n 'pxf' => 'application/octet-stream',\n 'pya' => 'audio/vnd.ms-playready.media.pya',\n 'pyo' => 'model/vnd.pytha.pyox',\n 'pyox' => 'model/vnd.pytha.pyox',\n 'pyv' => 'video/vnd.ms-playready.media.pyv',\n 'qam' => 'application/vnd.epson.quickanime',\n 'qbo' => 'application/vnd.intu.qbo',\n 'qfx' => 'application/vnd.intu.qfx',\n 'qps' => 'application/vnd.publishare-delta-tree',\n 'qt' => 'video/quicktime',\n 'qwd' => 'application/vnd.quark.quarkxpress',\n 'qwt' => 'application/vnd.quark.quarkxpress',\n 'qxb' => 'application/vnd.quark.quarkxpress',\n 'qxd' => 'application/vnd.quark.quarkxpress',\n 'qxl' => 'application/vnd.quark.quarkxpress',\n 'qxt' => 'application/vnd.quark.quarkxpress',\n 'ra' => 'audio/x-realaudio',\n 'ram' => 'audio/x-pn-realaudio',\n 'raml' => 'application/raml+yaml',\n 'rapd' => 'application/route-apd+xml',\n 'rar' => 'application/x-rar',\n 'ras' => 'image/x-cmu-raster',\n 'rcprofile' => 'application/vnd.ipunplugged.rcprofile',\n 'rdf' => 'application/rdf+xml',\n 'rdz' => 'application/vnd.data-vision.rdz',\n 'relo' => 'application/p2p-overlay+xml',\n 'rep' => 'application/vnd.businessobjects',\n 'res' => 'application/x-dtbresource+xml',\n 'rgb' => 'image/x-rgb',\n 'rif' => 'application/reginfo+xml',\n 'rip' => 'audio/vnd.rip',\n 'ris' => 'application/x-research-info-systems',\n 'rl' => 'application/resource-lists+xml',\n 'rlc' => 'image/vnd.fujixerox.edmics-rlc',\n 'rld' => 'application/resource-lists-diff+xml',\n 'rm' => 'audio/x-pn-realaudio',\n 'rmi' => 'audio/midi',\n 'rmp' => 'audio/x-pn-realaudio-plugin',\n 'rms' => 'application/vnd.jcp.javame.midlet-rms',\n 'rmvb' => 'application/vnd.rn-realmedia-vbr',\n 'rnc' => 'application/relax-ng-compact-syntax',\n 'rng' => 'application/xml',\n 'roa' => 'application/rpki-roa',\n 'roff' => 'text/troff',\n 'rp9' => 'application/vnd.cloanto.rp9',\n 'rpm' => 'audio/x-pn-realaudio-plugin',\n 'rpss' => 'application/vnd.nokia.radio-presets',\n 'rpst' => 'application/vnd.nokia.radio-preset',\n 'rq' => 'application/sparql-query',\n 'rs' => 'application/rls-services+xml',\n 'rsa' => 'application/x-pkcs7',\n 'rsat' => 'application/atsc-rsat+xml',\n 'rsd' => 'application/rsd+xml',\n 'rsheet' => 'application/urc-ressheet+xml',\n 'rss' => 'application/rss+xml',\n 'rtf' => 'text/rtf',\n 'rtx' => 'text/richtext',\n 'run' => 'application/x-makeself',\n 'rusd' => 'application/route-usd+xml',\n 'rv' => 'video/vnd.rn-realvideo',\n 's' => 'text/x-asm',\n 's3m' => 'audio/s3m',\n 'saf' => 'application/vnd.yamaha.smaf-audio',\n 'sass' => 'text/x-sass',\n 'sbml' => 'application/sbml+xml',\n 'sc' => 'application/vnd.ibm.secure-container',\n 'scd' => 'application/x-msschedule',\n 'scm' => 'application/vnd.lotus-screencam',\n 'scq' => 'application/scvp-cv-request',\n 'scs' => 'application/scvp-cv-response',\n 'scss' => 'text/x-scss',\n 'scurl' => 'text/vnd.curl.scurl',\n 'sda' => 'application/vnd.stardivision.draw',\n 'sdc' => 'application/vnd.stardivision.calc',\n 'sdd' => 'application/vnd.stardivision.impress',\n 'sdkd' => 'application/vnd.solent.sdkm+xml',\n 'sdkm' => 'application/vnd.solent.sdkm+xml',\n 'sdp' => 'application/sdp',\n 'sdw' => 'application/vnd.stardivision.writer',\n 'sea' => 'application/octet-stream',\n 'see' => 'application/vnd.seemail',\n 'seed' => 'application/vnd.fdsn.seed',\n 'sema' => 'application/vnd.sema',\n 'semd' => 'application/vnd.semd',\n 'semf' => 'application/vnd.semf',\n 'senmlx' => 'application/senml+xml',\n 'sensmlx' => 'application/sensml+xml',\n 'ser' => 'application/java-serialized-object',\n 'setpay' => 'application/set-payment-initiation',\n 'setreg' => 'application/set-registration-initiation',\n 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data',\n 'sfs' => 'application/vnd.spotfire.sfs',\n 'sfv' => 'text/x-sfv',\n 'sgi' => 'image/sgi',\n 'sgl' => 'application/vnd.stardivision.writer-global',\n 'sgm' => 'text/sgml',\n 'sgml' => 'text/sgml',\n 'sh' => 'application/x-sh',\n 'shar' => 'application/x-shar',\n 'shex' => 'text/shex',\n 'shf' => 'application/shf+xml',\n 'shtml' => 'text/html',\n 'sid' => 'image/x-mrsid-image',\n 'sieve' => 'application/sieve',\n 'sig' => 'application/pgp-signature',\n 'sil' => 'audio/silk',\n 'silo' => 'model/mesh',\n 'sis' => 'application/vnd.symbian.install',\n 'sisx' => 'application/vnd.symbian.install',\n 'sit' => 'application/x-stuffit',\n 'sitx' => 'application/x-stuffitx',\n 'siv' => 'application/sieve',\n 'skd' => 'application/vnd.koan',\n 'skm' => 'application/vnd.koan',\n 'skp' => 'application/vnd.koan',\n 'skt' => 'application/vnd.koan',\n 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12',\n 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',\n 'slim' => 'text/slim',\n 'slm' => 'text/slim',\n 'sls' => 'application/route-s-tsid+xml',\n 'slt' => 'application/vnd.epson.salt',\n 'sm' => 'application/vnd.stepmania.stepchart',\n 'smf' => 'application/vnd.stardivision.math',\n 'smi' => 'application/smil',\n 'smil' => 'application/smil',\n 'smv' => 'video/x-smv',\n 'smzip' => 'application/vnd.stepmania.package',\n 'snd' => 'audio/basic',\n 'snf' => 'application/x-font-snf',\n 'so' => 'application/octet-stream',\n 'spc' => 'application/x-pkcs7-certificates',\n 'spdx' => 'text/spdx',\n 'spf' => 'application/vnd.yamaha.smaf-phrase',\n 'spl' => 'application/x-futuresplash',\n 'spot' => 'text/vnd.in3d.spot',\n 'spp' => 'application/scvp-vp-response',\n 'spq' => 'application/scvp-vp-request',\n 'spx' => 'audio/ogg',\n 'sql' => 'application/x-sql',\n 'src' => 'application/x-wais-source',\n 'srt' => 'application/x-subrip',\n 'sru' => 'application/sru+xml',\n 'srx' => 'application/sparql-results+xml',\n 'ssdl' => 'application/ssdl+xml',\n 'sse' => 'application/vnd.kodak-descriptor',\n 'ssf' => 'application/vnd.epson.ssf',\n 'ssml' => 'application/ssml+xml',\n 'sst' => 'application/octet-stream',\n 'st' => 'application/vnd.sailingtracker.track',\n 'stc' => 'application/vnd.sun.xml.calc.template',\n 'std' => 'application/vnd.sun.xml.draw.template',\n 'step' => 'application/STEP',\n 'stf' => 'application/vnd.wt.stf',\n 'sti' => 'application/vnd.sun.xml.impress.template',\n 'stk' => 'application/hyperstudio',\n 'stl' => 'model/stl',\n 'stp' => 'application/STEP',\n 'stpx' => 'model/step+xml',\n 'stpxz' => 'model/step-xml+zip',\n 'stpz' => 'model/step+zip',\n 'str' => 'application/vnd.pg.format',\n 'stw' => 'application/vnd.sun.xml.writer.template',\n 'styl' => 'text/stylus',\n 'stylus' => 'text/stylus',\n 'sub' => 'text/vnd.dvb.subtitle',\n 'sus' => 'application/vnd.sus-calendar',\n 'susp' => 'application/vnd.sus-calendar',\n 'sv4cpio' => 'application/x-sv4cpio',\n 'sv4crc' => 'application/x-sv4crc',\n 'svc' => 'application/vnd.dvb.service',\n 'svd' => 'application/vnd.svd',\n 'svg' => 'image/svg+xml',\n 'svgz' => 'image/svg+xml',\n 'swa' => 'application/x-director',\n 'swf' => 'application/x-shockwave-flash',\n 'swi' => 'application/vnd.aristanetworks.swi',\n 'swidtag' => 'application/swid+xml',\n 'sxc' => 'application/vnd.sun.xml.calc',\n 'sxd' => 'application/vnd.sun.xml.draw',\n 'sxg' => 'application/vnd.sun.xml.writer.global',\n 'sxi' => 'application/vnd.sun.xml.impress',\n 'sxm' => 'application/vnd.sun.xml.math',\n 'sxw' => 'application/vnd.sun.xml.writer',\n 't' => 'text/troff',\n 't3' => 'application/x-t3vm-image',\n 't38' => 'image/t38',\n 'taglet' => 'application/vnd.mynfc',\n 'tao' => 'application/vnd.tao.intent-module-archive',\n 'tap' => 'image/vnd.tencent.tap',\n 'tar' => 'application/x-tar',\n 'tcap' => 'application/vnd.3gpp2.tcap',\n 'tcl' => 'application/x-tcl',\n 'td' => 'application/urc-targetdesc+xml',\n 'teacher' => 'application/vnd.smart.teacher',\n 'tei' => 'application/tei+xml',\n 'teicorpus' => 'application/tei+xml',\n 'tex' => 'application/x-tex',\n 'texi' => 'application/x-texinfo',\n 'texinfo' => 'application/x-texinfo',\n 'text' => 'text/plain',\n 'tfi' => 'application/thraud+xml',\n 'tfm' => 'application/x-tex-tfm',\n 'tfx' => 'image/tiff-fx',\n 'tga' => 'image/x-tga',\n 'tgz' => 'application/x-tar',\n 'thmx' => 'application/vnd.ms-officetheme',\n 'tif' => 'image/tiff',\n 'tiff' => 'image/tiff',\n 'tk' => 'application/x-tcl',\n 'tmo' => 'application/vnd.tmobile-livetv',\n 'toml' => 'application/toml',\n 'torrent' => 'application/x-bittorrent',\n 'tpl' => 'application/vnd.groove-tool-template',\n 'tpt' => 'application/vnd.trid.tpt',\n 'tr' => 'text/troff',\n 'tra' => 'application/vnd.trueapp',\n 'trig' => 'application/trig',\n 'trm' => 'application/x-msterminal',\n 'ts' => 'video/mp2t',\n 'tsd' => 'application/timestamped-data',\n 'tsv' => 'text/tab-separated-values',\n 'ttc' => 'font/collection',\n 'ttf' => 'font/ttf',\n 'ttl' => 'text/turtle',\n 'ttml' => 'application/ttml+xml',\n 'twd' => 'application/vnd.simtech-mindmapper',\n 'twds' => 'application/vnd.simtech-mindmapper',\n 'txd' => 'application/vnd.genomatix.tuxedo',\n 'txf' => 'application/vnd.mobius.txf',\n 'txt' => 'text/plain',\n 'u3d' => 'model/u3d',\n 'u8dsn' => 'message/global-delivery-status',\n 'u8hdr' => 'message/global-headers',\n 'u8mdn' => 'message/global-disposition-notification',\n 'u8msg' => 'message/global',\n 'u32' => 'application/x-authorware-bin',\n 'ubj' => 'application/ubjson',\n 'udeb' => 'application/x-debian-package',\n 'ufd' => 'application/vnd.ufdl',\n 'ufdl' => 'application/vnd.ufdl',\n 'ulx' => 'application/x-glulx',\n 'umj' => 'application/vnd.umajin',\n 'unityweb' => 'application/vnd.unity',\n 'uo' => 'application/vnd.uoml+xml',\n 'uoml' => 'application/vnd.uoml+xml',\n 'uri' => 'text/uri-list',\n 'uris' => 'text/uri-list',\n 'urls' => 'text/uri-list',\n 'usda' => 'model/vnd.usda',\n 'usdz' => 'model/vnd.usdz+zip',\n 'ustar' => 'application/x-ustar',\n 'utz' => 'application/vnd.uiq.theme',\n 'uu' => 'text/x-uuencode',\n 'uva' => 'audio/vnd.dece.audio',\n 'uvd' => 'application/vnd.dece.data',\n 'uvf' => 'application/vnd.dece.data',\n 'uvg' => 'image/vnd.dece.graphic',\n 'uvh' => 'video/vnd.dece.hd',\n 'uvi' => 'image/vnd.dece.graphic',\n 'uvm' => 'video/vnd.dece.mobile',\n 'uvp' => 'video/vnd.dece.pd',\n 'uvs' => 'video/vnd.dece.sd',\n 'uvt' => 'application/vnd.dece.ttml+xml',\n 'uvu' => 'video/vnd.uvvu.mp4',\n 'uvv' => 'video/vnd.dece.video',\n 'uvva' => 'audio/vnd.dece.audio',\n 'uvvd' => 'application/vnd.dece.data',\n 'uvvf' => 'application/vnd.dece.data',\n 'uvvg' => 'image/vnd.dece.graphic',\n 'uvvh' => 'video/vnd.dece.hd',\n 'uvvi' => 'image/vnd.dece.graphic',\n 'uvvm' => 'video/vnd.dece.mobile',\n 'uvvp' => 'video/vnd.dece.pd',\n 'uvvs' => 'video/vnd.dece.sd',\n 'uvvt' => 'application/vnd.dece.ttml+xml',\n 'uvvu' => 'video/vnd.uvvu.mp4',\n 'uvvv' => 'video/vnd.dece.video',\n 'uvvx' => 'application/vnd.dece.unspecified',\n 'uvvz' => 'application/vnd.dece.zip',\n 'uvx' => 'application/vnd.dece.unspecified',\n 'uvz' => 'application/vnd.dece.zip',\n 'vbox' => 'application/x-virtualbox-vbox',\n 'vbox-extpack' => 'application/x-virtualbox-vbox-extpack',\n 'vcard' => 'text/vcard',\n 'vcd' => 'application/x-cdlink',\n 'vcf' => 'text/x-vcard',\n 'vcg' => 'application/vnd.groove-vcard',\n 'vcs' => 'text/x-vcalendar',\n 'vcx' => 'application/vnd.vcx',\n 'vdi' => 'application/x-virtualbox-vdi',\n 'vds' => 'model/vnd.sap.vds',\n 'vhd' => 'application/x-virtualbox-vhd',\n 'vis' => 'application/vnd.visionary',\n 'viv' => 'video/vnd.vivo',\n 'vlc' => 'application/videolan',\n 'vmdk' => 'application/x-virtualbox-vmdk',\n 'vob' => 'video/x-ms-vob',\n 'vor' => 'application/vnd.stardivision.writer',\n 'vox' => 'application/x-authorware-bin',\n 'vrml' => 'model/vrml',\n 'vsd' => 'application/vnd.visio',\n 'vsf' => 'application/vnd.vsf',\n 'vss' => 'application/vnd.visio',\n 'vst' => 'application/vnd.visio',\n 'vsw' => 'application/vnd.visio',\n 'vtf' => 'image/vnd.valve.source.texture',\n 'vtt' => 'text/vtt',\n 'vtu' => 'model/vnd.vtu',\n 'vxml' => 'application/voicexml+xml',\n 'w3d' => 'application/x-director',\n 'wad' => 'application/x-doom',\n 'wadl' => 'application/vnd.sun.wadl+xml',\n 'war' => 'application/java-archive',\n 'wasm' => 'application/wasm',\n 'wav' => 'audio/x-wav',\n 'wax' => 'audio/x-ms-wax',\n 'wbmp' => 'image/vnd.wap.wbmp',\n 'wbs' => 'application/vnd.criticaltools.wbs+xml',\n 'wbxml' => 'application/wbxml',\n 'wcm' => 'application/vnd.ms-works',\n 'wdb' => 'application/vnd.ms-works',\n 'wdp' => 'image/vnd.ms-photo',\n 'weba' => 'audio/webm',\n 'webapp' => 'application/x-web-app-manifest+json',\n 'webm' => 'video/webm',\n 'webmanifest' => 'application/manifest+json',\n 'webp' => 'image/webp',\n 'wg' => 'application/vnd.pmi.widget',\n 'wgsl' => 'text/wgsl',\n 'wgt' => 'application/widget',\n 'wif' => 'application/watcherinfo+xml',\n 'wks' => 'application/vnd.ms-works',\n 'wm' => 'video/x-ms-wm',\n 'wma' => 'audio/x-ms-wma',\n 'wmd' => 'application/x-ms-wmd',\n 'wmf' => 'image/wmf',\n 'wml' => 'text/vnd.wap.wml',\n 'wmlc' => 'application/wmlc',\n 'wmls' => 'text/vnd.wap.wmlscript',\n 'wmlsc' => 'application/vnd.wap.wmlscriptc',\n 'wmv' => 'video/x-ms-wmv',\n 'wmx' => 'video/x-ms-wmx',\n 'wmz' => 'application/x-msmetafile',\n 'woff' => 'font/woff',\n 'woff2' => 'font/woff2',\n 'word' => 'application/msword',\n 'wpd' => 'application/vnd.wordperfect',\n 'wpl' => 'application/vnd.ms-wpl',\n 'wps' => 'application/vnd.ms-works',\n 'wqd' => 'application/vnd.wqd',\n 'wri' => 'application/x-mswrite',\n 'wrl' => 'model/vrml',\n 'wsc' => 'message/vnd.wfa.wsc',\n 'wsdl' => 'application/wsdl+xml',\n 'wspolicy' => 'application/wspolicy+xml',\n 'wtb' => 'application/vnd.webturbo',\n 'wvx' => 'video/x-ms-wvx',\n 'x3d' => 'model/x3d+xml',\n 'x3db' => 'model/x3d+fastinfoset',\n 'x3dbz' => 'model/x3d+binary',\n 'x3dv' => 'model/x3d-vrml',\n 'x3dvz' => 'model/x3d+vrml',\n 'x3dz' => 'model/x3d+xml',\n 'x32' => 'application/x-authorware-bin',\n 'x_b' => 'model/vnd.parasolid.transmit.binary',\n 'x_t' => 'model/vnd.parasolid.transmit.text',\n 'xaml' => 'application/xaml+xml',\n 'xap' => 'application/x-silverlight-app',\n 'xar' => 'application/vnd.xara',\n 'xav' => 'application/xcap-att+xml',\n 'xbap' => 'application/x-ms-xbap',\n 'xbd' => 'application/vnd.fujixerox.docuworks.binder',\n 'xbm' => 'image/x-xbitmap',\n 'xca' => 'application/xcap-caps+xml',\n 'xcs' => 'application/calendar+xml',\n 'xdf' => 'application/xcap-diff+xml',\n 'xdm' => 'application/vnd.syncml.dm+xml',\n 'xdp' => 'application/vnd.adobe.xdp+xml',\n 'xdssc' => 'application/dssc+xml',\n 'xdw' => 'application/vnd.fujixerox.docuworks',\n 'xel' => 'application/xcap-el+xml',\n 'xenc' => 'application/xenc+xml',\n 'xer' => 'application/patch-ops-error+xml',\n 'xfdf' => 'application/xfdf',\n 'xfdl' => 'application/vnd.xfdl',\n 'xht' => 'application/xhtml+xml',\n 'xhtm' => 'application/vnd.pwg-xhtml-print+xml',\n 'xhtml' => 'application/xhtml+xml',\n 'xhvml' => 'application/xv+xml',\n 'xif' => 'image/vnd.xiff',\n 'xl' => 'application/excel',\n 'xla' => 'application/vnd.ms-excel',\n 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',\n 'xlc' => 'application/vnd.ms-excel',\n 'xlf' => 'application/xliff+xml',\n 'xlm' => 'application/vnd.ms-excel',\n 'xls' => 'application/vnd.ms-excel',\n 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',\n 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',\n 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'xlt' => 'application/vnd.ms-excel',\n 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',\n 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',\n 'xlw' => 'application/vnd.ms-excel',\n 'xm' => 'audio/xm',\n 'xml' => 'application/xml',\n 'xns' => 'application/xcap-ns+xml',\n 'xo' => 'application/vnd.olpc-sugar',\n 'xop' => 'application/xop+xml',\n 'xpi' => 'application/x-xpinstall',\n 'xpl' => 'application/xproc+xml',\n 'xpm' => 'image/x-xpixmap',\n 'xpr' => 'application/vnd.is-xpr',\n 'xps' => 'application/vnd.ms-xpsdocument',\n 'xpw' => 'application/vnd.intercon.formnet',\n 'xpx' => 'application/vnd.intercon.formnet',\n 'xsd' => 'application/xml',\n 'xsf' => 'application/prs.xsf+xml',\n 'xsl' => 'application/xml',\n 'xslt' => 'application/xslt+xml',\n 'xsm' => 'application/vnd.syncml+xml',\n 'xspf' => 'application/xspf+xml',\n 'xul' => 'application/vnd.mozilla.xul+xml',\n 'xvm' => 'application/xv+xml',\n 'xvml' => 'application/xv+xml',\n 'xwd' => 'image/x-xwindowdump',\n 'xyz' => 'chemical/x-xyz',\n 'xz' => 'application/x-xz',\n 'yaml' => 'text/yaml',\n 'yang' => 'application/yang',\n 'yin' => 'application/yin+xml',\n 'yml' => 'text/yaml',\n 'ymp' => 'text/x-suse-ymp',\n 'z' => 'application/x-compress',\n 'z1' => 'application/x-zmachine',\n 'z2' => 'application/x-zmachine',\n 'z3' => 'application/x-zmachine',\n 'z4' => 'application/x-zmachine',\n 'z5' => 'application/x-zmachine',\n 'z6' => 'application/x-zmachine',\n 'z7' => 'application/x-zmachine',\n 'z8' => 'application/x-zmachine',\n 'zaz' => 'application/vnd.zzazz.deck+xml',\n 'zip' => 'application/zip',\n 'zir' => 'application/vnd.zul',\n 'zirz' => 'application/vnd.zul',\n 'zmm' => 'application/vnd.handheld-entertainment+xml',\n 'zsh' => 'text/x-scriptzsh',\n);
const EXTENSIONS_FOR_MIME_TYPES = array (\n 'application/andrew-inset' => \n array (\n 0 => 'ez',\n ),\n 'application/appinstaller' => \n array (\n 0 => 'appinstaller',\n ),\n 'application/applixware' => \n array (\n 0 => 'aw',\n ),\n 'application/appx' => \n array (\n 0 => 'appx',\n ),\n 'application/appxbundle' => \n array (\n 0 => 'appxbundle',\n ),\n 'application/atom+xml' => \n array (\n 0 => 'atom',\n ),\n 'application/atomcat+xml' => \n array (\n 0 => 'atomcat',\n ),\n 'application/atomdeleted+xml' => \n array (\n 0 => 'atomdeleted',\n ),\n 'application/atomsvc+xml' => \n array (\n 0 => 'atomsvc',\n ),\n 'application/atsc-dwd+xml' => \n array (\n 0 => 'dwd',\n ),\n 'application/atsc-held+xml' => \n array (\n 0 => 'held',\n ),\n 'application/atsc-rsat+xml' => \n array (\n 0 => 'rsat',\n ),\n 'application/automationml-aml+xml' => \n array (\n 0 => 'aml',\n ),\n 'application/automationml-amlx+zip' => \n array (\n 0 => 'amlx',\n ),\n 'application/bdoc' => \n array (\n 0 => 'bdoc',\n ),\n 'application/calendar+xml' => \n array (\n 0 => 'xcs',\n ),\n 'application/ccxml+xml' => \n array (\n 0 => 'ccxml',\n ),\n 'application/cdfx+xml' => \n array (\n 0 => 'cdfx',\n ),\n 'application/cdmi-capability' => \n array (\n 0 => 'cdmia',\n ),\n 'application/cdmi-container' => \n array (\n 0 => 'cdmic',\n ),\n 'application/cdmi-domain' => \n array (\n 0 => 'cdmid',\n ),\n 'application/cdmi-object' => \n array (\n 0 => 'cdmio',\n ),\n 'application/cdmi-queue' => \n array (\n 0 => 'cdmiq',\n ),\n 'application/cpl+xml' => \n array (\n 0 => 'cpl',\n ),\n 'application/cu-seeme' => \n array (\n 0 => 'cu',\n ),\n 'application/cwl' => \n array (\n 0 => 'cwl',\n ),\n 'application/dash+xml' => \n array (\n 0 => 'mpd',\n ),\n 'application/dash-patch+xml' => \n array (\n 0 => 'mpp',\n ),\n 'application/davmount+xml' => \n array (\n 0 => 'davmount',\n ),\n 'application/docbook+xml' => \n array (\n 0 => 'dbk',\n ),\n 'application/dssc+der' => \n array (\n 0 => 'dssc',\n ),\n 'application/dssc+xml' => \n array (\n 0 => 'xdssc',\n ),\n 'application/ecmascript' => \n array (\n 0 => 'ecma',\n ),\n 'application/emma+xml' => \n array (\n 0 => 'emma',\n ),\n 'application/emotionml+xml' => \n array (\n 0 => 'emotionml',\n ),\n 'application/epub+zip' => \n array (\n 0 => 'epub',\n ),\n 'application/exi' => \n array (\n 0 => 'exi',\n ),\n 'application/express' => \n array (\n 0 => 'exp',\n ),\n 'application/fdf' => \n array (\n 0 => 'fdf',\n ),\n 'application/fdt+xml' => \n array (\n 0 => 'fdt',\n ),\n 'application/font-tdpfr' => \n array (\n 0 => 'pfr',\n ),\n 'application/geo+json' => \n array (\n 0 => 'geojson',\n ),\n 'application/gml+xml' => \n array (\n 0 => 'gml',\n ),\n 'application/gpx+xml' => \n array (\n 0 => 'gpx',\n ),\n 'application/gxf' => \n array (\n 0 => 'gxf',\n ),\n 'application/gzip' => \n array (\n 0 => 'gz',\n 1 => 'gzip',\n ),\n 'application/hjson' => \n array (\n 0 => 'hjson',\n ),\n 'application/hyperstudio' => \n array (\n 0 => 'stk',\n ),\n 'application/inkml+xml' => \n array (\n 0 => 'ink',\n 1 => 'inkml',\n ),\n 'application/ipfix' => \n array (\n 0 => 'ipfix',\n ),\n 'application/its+xml' => \n array (\n 0 => 'its',\n ),\n 'application/java-archive' => \n array (\n 0 => 'jar',\n 1 => 'war',\n 2 => 'ear',\n ),\n 'application/java-serialized-object' => \n array (\n 0 => 'ser',\n ),\n 'application/java-vm' => \n array (\n 0 => 'class',\n ),\n 'application/javascript' => \n array (\n 0 => 'js',\n ),\n 'application/json' => \n array (\n 0 => 'json',\n 1 => 'map',\n ),\n 'application/json5' => \n array (\n 0 => 'json5',\n ),\n 'application/jsonml+json' => \n array (\n 0 => 'jsonml',\n ),\n 'application/ld+json' => \n array (\n 0 => 'jsonld',\n ),\n 'application/lgr+xml' => \n array (\n 0 => 'lgr',\n ),\n 'application/lost+xml' => \n array (\n 0 => 'lostxml',\n ),\n 'application/mac-binhex40' => \n array (\n 0 => 'hqx',\n ),\n 'application/mac-compactpro' => \n array (\n 0 => 'cpt',\n ),\n 'application/mads+xml' => \n array (\n 0 => 'mads',\n ),\n 'application/manifest+json' => \n array (\n 0 => 'webmanifest',\n ),\n 'application/marc' => \n array (\n 0 => 'mrc',\n ),\n 'application/marcxml+xml' => \n array (\n 0 => 'mrcx',\n ),\n 'application/mathematica' => \n array (\n 0 => 'ma',\n 1 => 'nb',\n 2 => 'mb',\n ),\n 'application/mathml+xml' => \n array (\n 0 => 'mathml',\n ),\n 'application/mbox' => \n array (\n 0 => 'mbox',\n ),\n 'application/media-policy-dataset+xml' => \n array (\n 0 => 'mpf',\n ),\n 'application/mediaservercontrol+xml' => \n array (\n 0 => 'mscml',\n ),\n 'application/metalink+xml' => \n array (\n 0 => 'metalink',\n ),\n 'application/metalink4+xml' => \n array (\n 0 => 'meta4',\n ),\n 'application/mets+xml' => \n array (\n 0 => 'mets',\n ),\n 'application/mmt-aei+xml' => \n array (\n 0 => 'maei',\n ),\n 'application/mmt-usd+xml' => \n array (\n 0 => 'musd',\n ),\n 'application/mods+xml' => \n array (\n 0 => 'mods',\n ),\n 'application/mp21' => \n array (\n 0 => 'm21',\n 1 => 'mp21',\n ),\n 'application/mp4' => \n array (\n 0 => 'mp4',\n 1 => 'mpg4',\n 2 => 'mp4s',\n 3 => 'm4p',\n ),\n 'application/msix' => \n array (\n 0 => 'msix',\n ),\n 'application/msixbundle' => \n array (\n 0 => 'msixbundle',\n ),\n 'application/msword' => \n array (\n 0 => 'doc',\n 1 => 'dot',\n 2 => 'word',\n ),\n 'application/mxf' => \n array (\n 0 => 'mxf',\n ),\n 'application/n-quads' => \n array (\n 0 => 'nq',\n ),\n 'application/n-triples' => \n array (\n 0 => 'nt',\n ),\n 'application/node' => \n array (\n 0 => 'cjs',\n ),\n 'application/octet-stream' => \n array (\n 0 => 'bin',\n 1 => 'dms',\n 2 => 'lrf',\n 3 => 'mar',\n 4 => 'so',\n 5 => 'dist',\n 6 => 'distz',\n 7 => 'pkg',\n 8 => 'bpk',\n 9 => 'dump',\n 10 => 'elc',\n 11 => 'deploy',\n 12 => 'exe',\n 13 => 'dll',\n 14 => 'deb',\n 15 => 'dmg',\n 16 => 'iso',\n 17 => 'img',\n 18 => 'msi',\n 19 => 'msp',\n 20 => 'msm',\n 21 => 'buffer',\n 22 => 'phar',\n 23 => 'lha',\n 24 => 'lzh',\n 25 => 'class',\n 26 => 'sea',\n 27 => 'dmn',\n 28 => 'bpmn',\n 29 => 'kdb',\n 30 => 'sst',\n 31 => 'csr',\n 32 => 'dst',\n 33 => 'pv',\n 34 => 'pxf',\n ),\n 'application/oda' => \n array (\n 0 => 'oda',\n ),\n 'application/oebps-package+xml' => \n array (\n 0 => 'opf',\n ),\n 'application/ogg' => \n array (\n 0 => 'ogx',\n ),\n 'application/omdoc+xml' => \n array (\n 0 => 'omdoc',\n ),\n 'application/onenote' => \n array (\n 0 => 'onetoc',\n 1 => 'onetoc2',\n 2 => 'onetmp',\n 3 => 'onepkg',\n ),\n 'application/oxps' => \n array (\n 0 => 'oxps',\n ),\n 'application/p2p-overlay+xml' => \n array (\n 0 => 'relo',\n ),\n 'application/patch-ops-error+xml' => \n array (\n 0 => 'xer',\n ),\n 'application/pdf' => \n array (\n 0 => 'pdf',\n 1 => 'ai',\n ),\n 'application/pgp-encrypted' => \n array (\n 0 => 'pgp',\n ),\n 'application/pgp-keys' => \n array (\n 0 => 'asc',\n ),\n 'application/pgp-signature' => \n array (\n 0 => 'sig',\n 1 => 'asc',\n ),\n 'application/pics-rules' => \n array (\n 0 => 'prf',\n ),\n 'application/pkcs10' => \n array (\n 0 => 'p10',\n ),\n 'application/pkcs7-mime' => \n array (\n 0 => 'p7m',\n 1 => 'p7c',\n ),\n 'application/pkcs7-signature' => \n array (\n 0 => 'p7s',\n ),\n 'application/pkcs8' => \n array (\n 0 => 'p8',\n ),\n 'application/pkix-attr-cert' => \n array (\n 0 => 'ac',\n ),\n 'application/pkix-cert' => \n array (\n 0 => 'cer',\n ),\n 'application/pkix-crl' => \n array (\n 0 => 'crl',\n ),\n 'application/pkix-pkipath' => \n array (\n 0 => 'pkipath',\n ),\n 'application/pkixcmp' => \n array (\n 0 => 'pki',\n ),\n 'application/pls+xml' => \n array (\n 0 => 'pls',\n ),\n 'application/postscript' => \n array (\n 0 => 'ai',\n 1 => 'eps',\n 2 => 'ps',\n ),\n 'application/provenance+xml' => \n array (\n 0 => 'provx',\n ),\n 'application/prs.cww' => \n array (\n 0 => 'cww',\n ),\n 'application/prs.xsf+xml' => \n array (\n 0 => 'xsf',\n ),\n 'application/pskc+xml' => \n array (\n 0 => 'pskcxml',\n ),\n 'application/raml+yaml' => \n array (\n 0 => 'raml',\n ),\n 'application/rdf+xml' => \n array (\n 0 => 'rdf',\n 1 => 'owl',\n ),\n 'application/reginfo+xml' => \n array (\n 0 => 'rif',\n ),\n 'application/relax-ng-compact-syntax' => \n array (\n 0 => 'rnc',\n ),\n 'application/resource-lists+xml' => \n array (\n 0 => 'rl',\n ),\n 'application/resource-lists-diff+xml' => \n array (\n 0 => 'rld',\n ),\n 'application/rls-services+xml' => \n array (\n 0 => 'rs',\n ),\n 'application/route-apd+xml' => \n array (\n 0 => 'rapd',\n ),\n 'application/route-s-tsid+xml' => \n array (\n 0 => 'sls',\n ),\n 'application/route-usd+xml' => \n array (\n 0 => 'rusd',\n ),\n 'application/rpki-ghostbusters' => \n array (\n 0 => 'gbr',\n ),\n 'application/rpki-manifest' => \n array (\n 0 => 'mft',\n ),\n 'application/rpki-roa' => \n array (\n 0 => 'roa',\n ),\n 'application/rsd+xml' => \n array (\n 0 => 'rsd',\n ),\n 'application/rss+xml' => \n array (\n 0 => 'rss',\n ),\n 'application/rtf' => \n array (\n 0 => 'rtf',\n ),\n 'application/sbml+xml' => \n array (\n 0 => 'sbml',\n ),\n 'application/scvp-cv-request' => \n array (\n 0 => 'scq',\n ),\n 'application/scvp-cv-response' => \n array (\n 0 => 'scs',\n ),\n 'application/scvp-vp-request' => \n array (\n 0 => 'spq',\n ),\n 'application/scvp-vp-response' => \n array (\n 0 => 'spp',\n ),\n 'application/sdp' => \n array (\n 0 => 'sdp',\n ),\n 'application/senml+xml' => \n array (\n 0 => 'senmlx',\n ),\n 'application/sensml+xml' => \n array (\n 0 => 'sensmlx',\n ),\n 'application/set-payment-initiation' => \n array (\n 0 => 'setpay',\n ),\n 'application/set-registration-initiation' => \n array (\n 0 => 'setreg',\n ),\n 'application/shf+xml' => \n array (\n 0 => 'shf',\n ),\n 'application/sieve' => \n array (\n 0 => 'siv',\n 1 => 'sieve',\n ),\n 'application/smil+xml' => \n array (\n 0 => 'smi',\n 1 => 'smil',\n ),\n 'application/sparql-query' => \n array (\n 0 => 'rq',\n ),\n 'application/sparql-results+xml' => \n array (\n 0 => 'srx',\n ),\n 'application/sql' => \n array (\n 0 => 'sql',\n ),\n 'application/srgs' => \n array (\n 0 => 'gram',\n ),\n 'application/srgs+xml' => \n array (\n 0 => 'grxml',\n ),\n 'application/sru+xml' => \n array (\n 0 => 'sru',\n ),\n 'application/ssdl+xml' => \n array (\n 0 => 'ssdl',\n ),\n 'application/ssml+xml' => \n array (\n 0 => 'ssml',\n ),\n 'application/swid+xml' => \n array (\n 0 => 'swidtag',\n ),\n 'application/tei+xml' => \n array (\n 0 => 'tei',\n 1 => 'teicorpus',\n ),\n 'application/thraud+xml' => \n array (\n 0 => 'tfi',\n ),\n 'application/timestamped-data' => \n array (\n 0 => 'tsd',\n ),\n 'application/toml' => \n array (\n 0 => 'toml',\n ),\n 'application/trig' => \n array (\n 0 => 'trig',\n ),\n 'application/ttml+xml' => \n array (\n 0 => 'ttml',\n ),\n 'application/ubjson' => \n array (\n 0 => 'ubj',\n ),\n 'application/urc-ressheet+xml' => \n array (\n 0 => 'rsheet',\n ),\n 'application/urc-targetdesc+xml' => \n array (\n 0 => 'td',\n ),\n 'application/vnd.1000minds.decision-model+xml' => \n array (\n 0 => '1km',\n ),\n 'application/vnd.3gpp.pic-bw-large' => \n array (\n 0 => 'plb',\n ),\n 'application/vnd.3gpp.pic-bw-small' => \n array (\n 0 => 'psb',\n ),\n 'application/vnd.3gpp.pic-bw-var' => \n array (\n 0 => 'pvb',\n ),\n 'application/vnd.3gpp2.tcap' => \n array (\n 0 => 'tcap',\n ),\n 'application/vnd.3m.post-it-notes' => \n array (\n 0 => 'pwn',\n ),\n 'application/vnd.accpac.simply.aso' => \n array (\n 0 => 'aso',\n ),\n 'application/vnd.accpac.simply.imp' => \n array (\n 0 => 'imp',\n ),\n 'application/vnd.acucobol' => \n array (\n 0 => 'acu',\n ),\n 'application/vnd.acucorp' => \n array (\n 0 => 'atc',\n 1 => 'acutc',\n ),\n 'application/vnd.adobe.air-application-installer-package+zip' => \n array (\n 0 => 'air',\n ),\n 'application/vnd.adobe.formscentral.fcdt' => \n array (\n 0 => 'fcdt',\n ),\n 'application/vnd.adobe.fxp' => \n array (\n 0 => 'fxp',\n 1 => 'fxpl',\n ),\n 'application/vnd.adobe.xdp+xml' => \n array (\n 0 => 'xdp',\n ),\n 'application/vnd.adobe.xfdf' => \n array (\n 0 => 'xfdf',\n ),\n 'application/vnd.age' => \n array (\n 0 => 'age',\n ),\n 'application/vnd.ahead.space' => \n array (\n 0 => 'ahead',\n ),\n 'application/vnd.airzip.filesecure.azf' => \n array (\n 0 => 'azf',\n ),\n 'application/vnd.airzip.filesecure.azs' => \n array (\n 0 => 'azs',\n ),\n 'application/vnd.amazon.ebook' => \n array (\n 0 => 'azw',\n ),\n 'application/vnd.americandynamics.acc' => \n array (\n 0 => 'acc',\n ),\n 'application/vnd.amiga.ami' => \n array (\n 0 => 'ami',\n ),\n 'application/vnd.android.package-archive' => \n array (\n 0 => 'apk',\n ),\n 'application/vnd.anser-web-certificate-issue-initiation' => \n array (\n 0 => 'cii',\n ),\n 'application/vnd.anser-web-funds-transfer-initiation' => \n array (\n 0 => 'fti',\n ),\n 'application/vnd.antix.game-component' => \n array (\n 0 => 'atx',\n ),\n 'application/vnd.apple.installer+xml' => \n array (\n 0 => 'mpkg',\n ),\n 'application/vnd.apple.keynote' => \n array (\n 0 => 'key',\n ),\n 'application/vnd.apple.mpegurl' => \n array (\n 0 => 'm3u8',\n ),\n 'application/vnd.apple.numbers' => \n array (\n 0 => 'numbers',\n ),\n 'application/vnd.apple.pages' => \n array (\n 0 => 'pages',\n ),\n 'application/vnd.apple.pkpass' => \n array (\n 0 => 'pkpass',\n ),\n 'application/vnd.aristanetworks.swi' => \n array (\n 0 => 'swi',\n ),\n 'application/vnd.astraea-software.iota' => \n array (\n 0 => 'iota',\n ),\n 'application/vnd.audiograph' => \n array (\n 0 => 'aep',\n ),\n 'application/vnd.balsamiq.bmml+xml' => \n array (\n 0 => 'bmml',\n ),\n 'application/vnd.blueice.multipass' => \n array (\n 0 => 'mpm',\n ),\n 'application/vnd.bmi' => \n array (\n 0 => 'bmi',\n ),\n 'application/vnd.businessobjects' => \n array (\n 0 => 'rep',\n ),\n 'application/vnd.chemdraw+xml' => \n array (\n 0 => 'cdxml',\n ),\n 'application/vnd.chipnuts.karaoke-mmd' => \n array (\n 0 => 'mmd',\n ),\n 'application/vnd.cinderella' => \n array (\n 0 => 'cdy',\n ),\n 'application/vnd.citationstyles.style+xml' => \n array (\n 0 => 'csl',\n ),\n 'application/vnd.claymore' => \n array (\n 0 => 'cla',\n ),\n 'application/vnd.cloanto.rp9' => \n array (\n 0 => 'rp9',\n ),\n 'application/vnd.clonk.c4group' => \n array (\n 0 => 'c4g',\n 1 => 'c4d',\n 2 => 'c4f',\n 3 => 'c4p',\n 4 => 'c4u',\n ),\n 'application/vnd.cluetrust.cartomobile-config' => \n array (\n 0 => 'c11amc',\n ),\n 'application/vnd.cluetrust.cartomobile-config-pkg' => \n array (\n 0 => 'c11amz',\n ),\n 'application/vnd.commonspace' => \n array (\n 0 => 'csp',\n ),\n 'application/vnd.contact.cmsg' => \n array (\n 0 => 'cdbcmsg',\n ),\n 'application/vnd.cosmocaller' => \n array (\n 0 => 'cmc',\n ),\n 'application/vnd.crick.clicker' => \n array (\n 0 => 'clkx',\n ),\n 'application/vnd.crick.clicker.keyboard' => \n array (\n 0 => 'clkk',\n ),\n 'application/vnd.crick.clicker.palette' => \n array (\n 0 => 'clkp',\n ),\n 'application/vnd.crick.clicker.template' => \n array (\n 0 => 'clkt',\n ),\n 'application/vnd.crick.clicker.wordbank' => \n array (\n 0 => 'clkw',\n ),\n 'application/vnd.criticaltools.wbs+xml' => \n array (\n 0 => 'wbs',\n ),\n 'application/vnd.ctc-posml' => \n array (\n 0 => 'pml',\n ),\n 'application/vnd.cups-ppd' => \n array (\n 0 => 'ppd',\n ),\n 'application/vnd.curl.car' => \n array (\n 0 => 'car',\n ),\n 'application/vnd.curl.pcurl' => \n array (\n 0 => 'pcurl',\n ),\n 'application/vnd.dart' => \n array (\n 0 => 'dart',\n ),\n 'application/vnd.data-vision.rdz' => \n array (\n 0 => 'rdz',\n ),\n 'application/vnd.dbf' => \n array (\n 0 => 'dbf',\n ),\n 'application/vnd.dece.data' => \n array (\n 0 => 'uvf',\n 1 => 'uvvf',\n 2 => 'uvd',\n 3 => 'uvvd',\n ),\n 'application/vnd.dece.ttml+xml' => \n array (\n 0 => 'uvt',\n 1 => 'uvvt',\n ),\n 'application/vnd.dece.unspecified' => \n array (\n 0 => 'uvx',\n 1 => 'uvvx',\n ),\n 'application/vnd.dece.zip' => \n array (\n 0 => 'uvz',\n 1 => 'uvvz',\n ),\n 'application/vnd.denovo.fcselayout-link' => \n array (\n 0 => 'fe_launch',\n ),\n 'application/vnd.dna' => \n array (\n 0 => 'dna',\n ),\n 'application/vnd.dolby.mlp' => \n array (\n 0 => 'mlp',\n ),\n 'application/vnd.dpgraph' => \n array (\n 0 => 'dpg',\n ),\n 'application/vnd.dreamfactory' => \n array (\n 0 => 'dfac',\n ),\n 'application/vnd.ds-keypoint' => \n array (\n 0 => 'kpxx',\n ),\n 'application/vnd.dvb.ait' => \n array (\n 0 => 'ait',\n ),\n 'application/vnd.dvb.service' => \n array (\n 0 => 'svc',\n ),\n 'application/vnd.dynageo' => \n array (\n 0 => 'geo',\n ),\n 'application/vnd.ecowin.chart' => \n array (\n 0 => 'mag',\n ),\n 'application/vnd.enliven' => \n array (\n 0 => 'nml',\n ),\n 'application/vnd.epson.esf' => \n array (\n 0 => 'esf',\n ),\n 'application/vnd.epson.msf' => \n array (\n 0 => 'msf',\n ),\n 'application/vnd.epson.quickanime' => \n array (\n 0 => 'qam',\n ),\n 'application/vnd.epson.salt' => \n array (\n 0 => 'slt',\n ),\n 'application/vnd.epson.ssf' => \n array (\n 0 => 'ssf',\n ),\n 'application/vnd.eszigno3+xml' => \n array (\n 0 => 'es3',\n 1 => 'et3',\n ),\n 'application/vnd.ezpix-album' => \n array (\n 0 => 'ez2',\n ),\n 'application/vnd.ezpix-package' => \n array (\n 0 => 'ez3',\n ),\n 'application/vnd.fdf' => \n array (\n 0 => 'fdf',\n ),\n 'application/vnd.fdsn.mseed' => \n array (\n 0 => 'mseed',\n ),\n 'application/vnd.fdsn.seed' => \n array (\n 0 => 'seed',\n 1 => 'dataless',\n ),\n 'application/vnd.flographit' => \n array (\n 0 => 'gph',\n ),\n 'application/vnd.fluxtime.clip' => \n array (\n 0 => 'ftc',\n ),\n 'application/vnd.framemaker' => \n array (\n 0 => 'fm',\n 1 => 'frame',\n 2 => 'maker',\n 3 => 'book',\n ),\n 'application/vnd.frogans.fnc' => \n array (\n 0 => 'fnc',\n ),\n 'application/vnd.frogans.ltf' => \n array (\n 0 => 'ltf',\n ),\n 'application/vnd.fsc.weblaunch' => \n array (\n 0 => 'fsc',\n ),\n 'application/vnd.fujitsu.oasys' => \n array (\n 0 => 'oas',\n ),\n 'application/vnd.fujitsu.oasys2' => \n array (\n 0 => 'oa2',\n ),\n 'application/vnd.fujitsu.oasys3' => \n array (\n 0 => 'oa3',\n ),\n 'application/vnd.fujitsu.oasysgp' => \n array (\n 0 => 'fg5',\n ),\n 'application/vnd.fujitsu.oasysprs' => \n array (\n 0 => 'bh2',\n ),\n 'application/vnd.fujixerox.ddd' => \n array (\n 0 => 'ddd',\n ),\n 'application/vnd.fujixerox.docuworks' => \n array (\n 0 => 'xdw',\n ),\n 'application/vnd.fujixerox.docuworks.binder' => \n array (\n 0 => 'xbd',\n ),\n 'application/vnd.fuzzysheet' => \n array (\n 0 => 'fzs',\n ),\n 'application/vnd.genomatix.tuxedo' => \n array (\n 0 => 'txd',\n ),\n 'application/vnd.geogebra.file' => \n array (\n 0 => 'ggb',\n ),\n 'application/vnd.geogebra.tool' => \n array (\n 0 => 'ggt',\n ),\n 'application/vnd.geometry-explorer' => \n array (\n 0 => 'gex',\n 1 => 'gre',\n ),\n 'application/vnd.geonext' => \n array (\n 0 => 'gxt',\n ),\n 'application/vnd.geoplan' => \n array (\n 0 => 'g2w',\n ),\n 'application/vnd.geospace' => \n array (\n 0 => 'g3w',\n ),\n 'application/vnd.gmx' => \n array (\n 0 => 'gmx',\n ),\n 'application/vnd.google-apps.document' => \n array (\n 0 => 'gdoc',\n ),\n 'application/vnd.google-apps.presentation' => \n array (\n 0 => 'gslides',\n ),\n 'application/vnd.google-apps.spreadsheet' => \n array (\n 0 => 'gsheet',\n ),\n 'application/vnd.google-earth.kml+xml' => \n array (\n 0 => 'kml',\n ),\n 'application/vnd.google-earth.kmz' => \n array (\n 0 => 'kmz',\n ),\n 'application/vnd.grafeq' => \n array (\n 0 => 'gqf',\n 1 => 'gqs',\n ),\n 'application/vnd.groove-account' => \n array (\n 0 => 'gac',\n ),\n 'application/vnd.groove-help' => \n array (\n 0 => 'ghf',\n ),\n 'application/vnd.groove-identity-message' => \n array (\n 0 => 'gim',\n ),\n 'application/vnd.groove-injector' => \n array (\n 0 => 'grv',\n ),\n 'application/vnd.groove-tool-message' => \n array (\n 0 => 'gtm',\n ),\n 'application/vnd.groove-tool-template' => \n array (\n 0 => 'tpl',\n ),\n 'application/vnd.groove-vcard' => \n array (\n 0 => 'vcg',\n ),\n 'application/vnd.hal+xml' => \n array (\n 0 => 'hal',\n ),\n 'application/vnd.handheld-entertainment+xml' => \n array (\n 0 => 'zmm',\n ),\n 'application/vnd.hbci' => \n array (\n 0 => 'hbci',\n ),\n 'application/vnd.hhe.lesson-player' => \n array (\n 0 => 'les',\n ),\n 'application/vnd.hp-hpgl' => \n array (\n 0 => 'hpgl',\n ),\n 'application/vnd.hp-hpid' => \n array (\n 0 => 'hpid',\n ),\n 'application/vnd.hp-hps' => \n array (\n 0 => 'hps',\n ),\n 'application/vnd.hp-jlyt' => \n array (\n 0 => 'jlt',\n ),\n 'application/vnd.hp-pcl' => \n array (\n 0 => 'pcl',\n ),\n 'application/vnd.hp-pclxl' => \n array (\n 0 => 'pclxl',\n ),\n 'application/vnd.hydrostatix.sof-data' => \n array (\n 0 => 'sfd-hdstx',\n ),\n 'application/vnd.ibm.minipay' => \n array (\n 0 => 'mpy',\n ),\n 'application/vnd.ibm.modcap' => \n array (\n 0 => 'afp',\n 1 => 'listafp',\n 2 => 'list3820',\n ),\n 'application/vnd.ibm.rights-management' => \n array (\n 0 => 'irm',\n ),\n 'application/vnd.ibm.secure-container' => \n array (\n 0 => 'sc',\n ),\n 'application/vnd.iccprofile' => \n array (\n 0 => 'icc',\n 1 => 'icm',\n ),\n 'application/vnd.igloader' => \n array (\n 0 => 'igl',\n ),\n 'application/vnd.immervision-ivp' => \n array (\n 0 => 'ivp',\n ),\n 'application/vnd.immervision-ivu' => \n array (\n 0 => 'ivu',\n ),\n 'application/vnd.insors.igm' => \n array (\n 0 => 'igm',\n ),\n 'application/vnd.intercon.formnet' => \n array (\n 0 => 'xpw',\n 1 => 'xpx',\n ),\n 'application/vnd.intergeo' => \n array (\n 0 => 'i2g',\n ),\n 'application/vnd.intu.qbo' => \n array (\n 0 => 'qbo',\n ),\n 'application/vnd.intu.qfx' => \n array (\n 0 => 'qfx',\n ),\n 'application/vnd.ipunplugged.rcprofile' => \n array (\n 0 => 'rcprofile',\n ),\n 'application/vnd.irepository.package+xml' => \n array (\n 0 => 'irp',\n ),\n 'application/vnd.is-xpr' => \n array (\n 0 => 'xpr',\n ),\n 'application/vnd.isac.fcs' => \n array (\n 0 => 'fcs',\n ),\n 'application/vnd.jam' => \n array (\n 0 => 'jam',\n ),\n 'application/vnd.jcp.javame.midlet-rms' => \n array (\n 0 => 'rms',\n ),\n 'application/vnd.jisp' => \n array (\n 0 => 'jisp',\n ),\n 'application/vnd.joost.joda-archive' => \n array (\n 0 => 'joda',\n ),\n 'application/vnd.kahootz' => \n array (\n 0 => 'ktz',\n 1 => 'ktr',\n ),\n 'application/vnd.kde.karbon' => \n array (\n 0 => 'karbon',\n ),\n 'application/vnd.kde.kchart' => \n array (\n 0 => 'chrt',\n ),\n 'application/vnd.kde.kformula' => \n array (\n 0 => 'kfo',\n ),\n 'application/vnd.kde.kivio' => \n array (\n 0 => 'flw',\n ),\n 'application/vnd.kde.kontour' => \n array (\n 0 => 'kon',\n ),\n 'application/vnd.kde.kpresenter' => \n array (\n 0 => 'kpr',\n 1 => 'kpt',\n ),\n 'application/vnd.kde.kspread' => \n array (\n 0 => 'ksp',\n ),\n 'application/vnd.kde.kword' => \n array (\n 0 => 'kwd',\n 1 => 'kwt',\n ),\n 'application/vnd.kenameaapp' => \n array (\n 0 => 'htke',\n ),\n 'application/vnd.kidspiration' => \n array (\n 0 => 'kia',\n ),\n 'application/vnd.kinar' => \n array (\n 0 => 'kne',\n 1 => 'knp',\n ),\n 'application/vnd.koan' => \n array (\n 0 => 'skp',\n 1 => 'skd',\n 2 => 'skt',\n 3 => 'skm',\n ),\n 'application/vnd.kodak-descriptor' => \n array (\n 0 => 'sse',\n ),\n 'application/vnd.las.las+xml' => \n array (\n 0 => 'lasxml',\n ),\n 'application/vnd.llamagraphics.life-balance.desktop' => \n array (\n 0 => 'lbd',\n ),\n 'application/vnd.llamagraphics.life-balance.exchange+xml' => \n array (\n 0 => 'lbe',\n ),\n 'application/vnd.lotus-1-2-3' => \n array (\n 0 => '123',\n ),\n 'application/vnd.lotus-approach' => \n array (\n 0 => 'apr',\n ),\n 'application/vnd.lotus-freelance' => \n array (\n 0 => 'pre',\n ),\n 'application/vnd.lotus-notes' => \n array (\n 0 => 'nsf',\n ),\n 'application/vnd.lotus-organizer' => \n array (\n 0 => 'org',\n ),\n 'application/vnd.lotus-screencam' => \n array (\n 0 => 'scm',\n ),\n 'application/vnd.lotus-wordpro' => \n array (\n 0 => 'lwp',\n ),\n 'application/vnd.macports.portpkg' => \n array (\n 0 => 'portpkg',\n ),\n 'application/vnd.mapbox-vector-tile' => \n array (\n 0 => 'mvt',\n ),\n 'application/vnd.mcd' => \n array (\n 0 => 'mcd',\n ),\n 'application/vnd.medcalcdata' => \n array (\n 0 => 'mc1',\n ),\n 'application/vnd.mediastation.cdkey' => \n array (\n 0 => 'cdkey',\n ),\n 'application/vnd.mfer' => \n array (\n 0 => 'mwf',\n ),\n 'application/vnd.mfmp' => \n array (\n 0 => 'mfm',\n ),\n 'application/vnd.micrografx.flo' => \n array (\n 0 => 'flo',\n ),\n 'application/vnd.micrografx.igx' => \n array (\n 0 => 'igx',\n ),\n 'application/vnd.mif' => \n array (\n 0 => 'mif',\n ),\n 'application/vnd.mobius.daf' => \n array (\n 0 => 'daf',\n ),\n 'application/vnd.mobius.dis' => \n array (\n 0 => 'dis',\n ),\n 'application/vnd.mobius.mbk' => \n array (\n 0 => 'mbk',\n ),\n 'application/vnd.mobius.mqy' => \n array (\n 0 => 'mqy',\n ),\n 'application/vnd.mobius.msl' => \n array (\n 0 => 'msl',\n ),\n 'application/vnd.mobius.plc' => \n array (\n 0 => 'plc',\n ),\n 'application/vnd.mobius.txf' => \n array (\n 0 => 'txf',\n ),\n 'application/vnd.mophun.application' => \n array (\n 0 => 'mpn',\n ),\n 'application/vnd.mophun.certificate' => \n array (\n 0 => 'mpc',\n ),\n 'application/vnd.mozilla.xul+xml' => \n array (\n 0 => 'xul',\n ),\n 'application/vnd.ms-artgalry' => \n array (\n 0 => 'cil',\n ),\n 'application/vnd.ms-cab-compressed' => \n array (\n 0 => 'cab',\n ),\n 'application/vnd.ms-excel' => \n array (\n 0 => 'xls',\n 1 => 'xlm',\n 2 => 'xla',\n 3 => 'xlc',\n 4 => 'xlt',\n 5 => 'xlw',\n ),\n 'application/vnd.ms-excel.addin.macroenabled.12' => \n array (\n 0 => 'xlam',\n ),\n 'application/vnd.ms-excel.sheet.binary.macroenabled.12' => \n array (\n 0 => 'xlsb',\n ),\n 'application/vnd.ms-excel.sheet.macroenabled.12' => \n array (\n 0 => 'xlsm',\n ),\n 'application/vnd.ms-excel.template.macroenabled.12' => \n array (\n 0 => 'xltm',\n ),\n 'application/vnd.ms-fontobject' => \n array (\n 0 => 'eot',\n ),\n 'application/vnd.ms-htmlhelp' => \n array (\n 0 => 'chm',\n ),\n 'application/vnd.ms-ims' => \n array (\n 0 => 'ims',\n ),\n 'application/vnd.ms-lrm' => \n array (\n 0 => 'lrm',\n ),\n 'application/vnd.ms-officetheme' => \n array (\n 0 => 'thmx',\n ),\n 'application/vnd.ms-outlook' => \n array (\n 0 => 'msg',\n ),\n 'application/vnd.ms-pki.seccat' => \n array (\n 0 => 'cat',\n ),\n 'application/vnd.ms-pki.stl' => \n array (\n 0 => 'stl',\n ),\n 'application/vnd.ms-powerpoint' => \n array (\n 0 => 'ppt',\n 1 => 'pps',\n 2 => 'pot',\n 3 => 'ppa',\n ),\n 'application/vnd.ms-powerpoint.addin.macroenabled.12' => \n array (\n 0 => 'ppam',\n ),\n 'application/vnd.ms-powerpoint.presentation.macroenabled.12' => \n array (\n 0 => 'pptm',\n ),\n 'application/vnd.ms-powerpoint.slide.macroenabled.12' => \n array (\n 0 => 'sldm',\n ),\n 'application/vnd.ms-powerpoint.slideshow.macroenabled.12' => \n array (\n 0 => 'ppsm',\n ),\n 'application/vnd.ms-powerpoint.template.macroenabled.12' => \n array (\n 0 => 'potm',\n ),\n 'application/vnd.ms-project' => \n array (\n 0 => 'mpp',\n 1 => 'mpt',\n ),\n 'application/vnd.ms-word.document.macroenabled.12' => \n array (\n 0 => 'docm',\n ),\n 'application/vnd.ms-word.template.macroenabled.12' => \n array (\n 0 => 'dotm',\n ),\n 'application/vnd.ms-works' => \n array (\n 0 => 'wps',\n 1 => 'wks',\n 2 => 'wcm',\n 3 => 'wdb',\n ),\n 'application/vnd.ms-wpl' => \n array (\n 0 => 'wpl',\n ),\n 'application/vnd.ms-xpsdocument' => \n array (\n 0 => 'xps',\n ),\n 'application/vnd.mseq' => \n array (\n 0 => 'mseq',\n ),\n 'application/vnd.musician' => \n array (\n 0 => 'mus',\n ),\n 'application/vnd.muvee.style' => \n array (\n 0 => 'msty',\n ),\n 'application/vnd.mynfc' => \n array (\n 0 => 'taglet',\n ),\n 'application/vnd.neurolanguage.nlu' => \n array (\n 0 => 'nlu',\n ),\n 'application/vnd.nitf' => \n array (\n 0 => 'ntf',\n 1 => 'nitf',\n ),\n 'application/vnd.noblenet-directory' => \n array (\n 0 => 'nnd',\n ),\n 'application/vnd.noblenet-sealer' => \n array (\n 0 => 'nns',\n ),\n 'application/vnd.noblenet-web' => \n array (\n 0 => 'nnw',\n ),\n 'application/vnd.nokia.n-gage.ac+xml' => \n array (\n 0 => 'ac',\n ),\n 'application/vnd.nokia.n-gage.data' => \n array (\n 0 => 'ngdat',\n ),\n 'application/vnd.nokia.n-gage.symbian.install' => \n array (\n 0 => 'n-gage',\n ),\n 'application/vnd.nokia.radio-preset' => \n array (\n 0 => 'rpst',\n ),\n 'application/vnd.nokia.radio-presets' => \n array (\n 0 => 'rpss',\n ),\n 'application/vnd.novadigm.edm' => \n array (\n 0 => 'edm',\n ),\n 'application/vnd.novadigm.edx' => \n array (\n 0 => 'edx',\n ),\n 'application/vnd.novadigm.ext' => \n array (\n 0 => 'ext',\n ),\n 'application/vnd.oasis.opendocument.chart' => \n array (\n 0 => 'odc',\n ),\n 'application/vnd.oasis.opendocument.chart-template' => \n array (\n 0 => 'otc',\n ),\n 'application/vnd.oasis.opendocument.database' => \n array (\n 0 => 'odb',\n ),\n 'application/vnd.oasis.opendocument.formula' => \n array (\n 0 => 'odf',\n ),\n 'application/vnd.oasis.opendocument.formula-template' => \n array (\n 0 => 'odft',\n ),\n 'application/vnd.oasis.opendocument.graphics' => \n array (\n 0 => 'odg',\n ),\n 'application/vnd.oasis.opendocument.graphics-template' => \n array (\n 0 => 'otg',\n ),\n 'application/vnd.oasis.opendocument.image' => \n array (\n 0 => 'odi',\n ),\n 'application/vnd.oasis.opendocument.image-template' => \n array (\n 0 => 'oti',\n ),\n 'application/vnd.oasis.opendocument.presentation' => \n array (\n 0 => 'odp',\n ),\n 'application/vnd.oasis.opendocument.presentation-template' => \n array (\n 0 => 'otp',\n ),\n 'application/vnd.oasis.opendocument.spreadsheet' => \n array (\n 0 => 'ods',\n ),\n 'application/vnd.oasis.opendocument.spreadsheet-template' => \n array (\n 0 => 'ots',\n ),\n 'application/vnd.oasis.opendocument.text' => \n array (\n 0 => 'odt',\n ),\n 'application/vnd.oasis.opendocument.text-master' => \n array (\n 0 => 'odm',\n ),\n 'application/vnd.oasis.opendocument.text-template' => \n array (\n 0 => 'ott',\n ),\n 'application/vnd.oasis.opendocument.text-web' => \n array (\n 0 => 'oth',\n ),\n 'application/vnd.olpc-sugar' => \n array (\n 0 => 'xo',\n ),\n 'application/vnd.oma.dd2+xml' => \n array (\n 0 => 'dd2',\n ),\n 'application/vnd.openblox.game+xml' => \n array (\n 0 => 'obgx',\n ),\n 'application/vnd.openofficeorg.extension' => \n array (\n 0 => 'oxt',\n ),\n 'application/vnd.openstreetmap.data+xml' => \n array (\n 0 => 'osm',\n ),\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => \n array (\n 0 => 'pptx',\n ),\n 'application/vnd.openxmlformats-officedocument.presentationml.slide' => \n array (\n 0 => 'sldx',\n ),\n 'application/vnd.openxmlformats-officedocument.presentationml.slideshow' => \n array (\n 0 => 'ppsx',\n ),\n 'application/vnd.openxmlformats-officedocument.presentationml.template' => \n array (\n 0 => 'potx',\n ),\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => \n array (\n 0 => 'xlsx',\n ),\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.template' => \n array (\n 0 => 'xltx',\n ),\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => \n array (\n 0 => 'docx',\n ),\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' => \n array (\n 0 => 'dotx',\n ),\n 'application/vnd.osgeo.mapguide.package' => \n array (\n 0 => 'mgp',\n ),\n 'application/vnd.osgi.dp' => \n array (\n 0 => 'dp',\n ),\n 'application/vnd.osgi.subsystem' => \n array (\n 0 => 'esa',\n ),\n 'application/vnd.palm' => \n array (\n 0 => 'pdb',\n 1 => 'pqa',\n 2 => 'oprc',\n ),\n 'application/vnd.pawaafile' => \n array (\n 0 => 'paw',\n ),\n 'application/vnd.pg.format' => \n array (\n 0 => 'str',\n ),\n 'application/vnd.pg.osasli' => \n array (\n 0 => 'ei6',\n ),\n 'application/vnd.picsel' => \n array (\n 0 => 'efif',\n ),\n 'application/vnd.pmi.widget' => \n array (\n 0 => 'wg',\n ),\n 'application/vnd.pocketlearn' => \n array (\n 0 => 'plf',\n ),\n 'application/vnd.powerbuilder6' => \n array (\n 0 => 'pbd',\n ),\n 'application/vnd.previewsystems.box' => \n array (\n 0 => 'box',\n ),\n 'application/vnd.proteus.magazine' => \n array (\n 0 => 'mgz',\n ),\n 'application/vnd.publishare-delta-tree' => \n array (\n 0 => 'qps',\n ),\n 'application/vnd.pvi.ptid1' => \n array (\n 0 => 'ptid',\n ),\n 'application/vnd.pwg-xhtml-print+xml' => \n array (\n 0 => 'xhtm',\n ),\n 'application/vnd.quark.quarkxpress' => \n array (\n 0 => 'qxd',\n 1 => 'qxt',\n 2 => 'qwd',\n 3 => 'qwt',\n 4 => 'qxl',\n 5 => 'qxb',\n ),\n 'application/vnd.rar' => \n array (\n 0 => 'rar',\n ),\n 'application/vnd.realvnc.bed' => \n array (\n 0 => 'bed',\n ),\n 'application/vnd.recordare.musicxml' => \n array (\n 0 => 'mxl',\n ),\n 'application/vnd.recordare.musicxml+xml' => \n array (\n 0 => 'musicxml',\n ),\n 'application/vnd.rig.cryptonote' => \n array (\n 0 => 'cryptonote',\n ),\n 'application/vnd.rim.cod' => \n array (\n 0 => 'cod',\n ),\n 'application/vnd.rn-realmedia' => \n array (\n 0 => 'rm',\n ),\n 'application/vnd.rn-realmedia-vbr' => \n array (\n 0 => 'rmvb',\n ),\n 'application/vnd.route66.link66+xml' => \n array (\n 0 => 'link66',\n ),\n 'application/vnd.sailingtracker.track' => \n array (\n 0 => 'st',\n ),\n 'application/vnd.seemail' => \n array (\n 0 => 'see',\n ),\n 'application/vnd.sema' => \n array (\n 0 => 'sema',\n ),\n 'application/vnd.semd' => \n array (\n 0 => 'semd',\n ),\n 'application/vnd.semf' => \n array (\n 0 => 'semf',\n ),\n 'application/vnd.shana.informed.formdata' => \n array (\n 0 => 'ifm',\n ),\n 'application/vnd.shana.informed.formtemplate' => \n array (\n 0 => 'itp',\n ),\n 'application/vnd.shana.informed.interchange' => \n array (\n 0 => 'iif',\n ),\n 'application/vnd.shana.informed.package' => \n array (\n 0 => 'ipk',\n ),\n 'application/vnd.simtech-mindmapper' => \n array (\n 0 => 'twd',\n 1 => 'twds',\n ),\n 'application/vnd.smaf' => \n array (\n 0 => 'mmf',\n ),\n 'application/vnd.smart.teacher' => \n array (\n 0 => 'teacher',\n ),\n 'application/vnd.software602.filler.form+xml' => \n array (\n 0 => 'fo',\n ),\n 'application/vnd.solent.sdkm+xml' => \n array (\n 0 => 'sdkm',\n 1 => 'sdkd',\n ),\n 'application/vnd.spotfire.dxp' => \n array (\n 0 => 'dxp',\n ),\n 'application/vnd.spotfire.sfs' => \n array (\n 0 => 'sfs',\n ),\n 'application/vnd.stardivision.calc' => \n array (\n 0 => 'sdc',\n ),\n 'application/vnd.stardivision.draw' => \n array (\n 0 => 'sda',\n ),\n 'application/vnd.stardivision.impress' => \n array (\n 0 => 'sdd',\n ),\n 'application/vnd.stardivision.math' => \n array (\n 0 => 'smf',\n ),\n 'application/vnd.stardivision.writer' => \n array (\n 0 => 'sdw',\n 1 => 'vor',\n ),\n 'application/vnd.stardivision.writer-global' => \n array (\n 0 => 'sgl',\n ),\n 'application/vnd.stepmania.package' => \n array (\n 0 => 'smzip',\n ),\n 'application/vnd.stepmania.stepchart' => \n array (\n 0 => 'sm',\n ),\n 'application/vnd.sun.wadl+xml' => \n array (\n 0 => 'wadl',\n ),\n 'application/vnd.sun.xml.calc' => \n array (\n 0 => 'sxc',\n ),\n 'application/vnd.sun.xml.calc.template' => \n array (\n 0 => 'stc',\n ),\n 'application/vnd.sun.xml.draw' => \n array (\n 0 => 'sxd',\n ),\n 'application/vnd.sun.xml.draw.template' => \n array (\n 0 => 'std',\n ),\n 'application/vnd.sun.xml.impress' => \n array (\n 0 => 'sxi',\n ),\n 'application/vnd.sun.xml.impress.template' => \n array (\n 0 => 'sti',\n ),\n 'application/vnd.sun.xml.math' => \n array (\n 0 => 'sxm',\n ),\n 'application/vnd.sun.xml.writer' => \n array (\n 0 => 'sxw',\n ),\n 'application/vnd.sun.xml.writer.global' => \n array (\n 0 => 'sxg',\n ),\n 'application/vnd.sun.xml.writer.template' => \n array (\n 0 => 'stw',\n ),\n 'application/vnd.sus-calendar' => \n array (\n 0 => 'sus',\n 1 => 'susp',\n ),\n 'application/vnd.svd' => \n array (\n 0 => 'svd',\n ),\n 'application/vnd.symbian.install' => \n array (\n 0 => 'sis',\n 1 => 'sisx',\n ),\n 'application/vnd.syncml+xml' => \n array (\n 0 => 'xsm',\n ),\n 'application/vnd.syncml.dm+wbxml' => \n array (\n 0 => 'bdm',\n ),\n 'application/vnd.syncml.dm+xml' => \n array (\n 0 => 'xdm',\n ),\n 'application/vnd.syncml.dmddf+xml' => \n array (\n 0 => 'ddf',\n ),\n 'application/vnd.tao.intent-module-archive' => \n array (\n 0 => 'tao',\n ),\n 'application/vnd.tcpdump.pcap' => \n array (\n 0 => 'pcap',\n 1 => 'cap',\n 2 => 'dmp',\n ),\n 'application/vnd.tmobile-livetv' => \n array (\n 0 => 'tmo',\n ),\n 'application/vnd.trid.tpt' => \n array (\n 0 => 'tpt',\n ),\n 'application/vnd.triscape.mxs' => \n array (\n 0 => 'mxs',\n ),\n 'application/vnd.trueapp' => \n array (\n 0 => 'tra',\n ),\n 'application/vnd.ufdl' => \n array (\n 0 => 'ufd',\n 1 => 'ufdl',\n ),\n 'application/vnd.uiq.theme' => \n array (\n 0 => 'utz',\n ),\n 'application/vnd.umajin' => \n array (\n 0 => 'umj',\n ),\n 'application/vnd.unity' => \n array (\n 0 => 'unityweb',\n ),\n 'application/vnd.uoml+xml' => \n array (\n 0 => 'uoml',\n 1 => 'uo',\n ),\n 'application/vnd.vcx' => \n array (\n 0 => 'vcx',\n ),\n 'application/vnd.visio' => \n array (\n 0 => 'vsd',\n 1 => 'vst',\n 2 => 'vss',\n 3 => 'vsw',\n ),\n 'application/vnd.visionary' => \n array (\n 0 => 'vis',\n ),\n 'application/vnd.vsf' => \n array (\n 0 => 'vsf',\n ),\n 'application/vnd.wap.wbxml' => \n array (\n 0 => 'wbxml',\n ),\n 'application/vnd.wap.wmlc' => \n array (\n 0 => 'wmlc',\n ),\n 'application/vnd.wap.wmlscriptc' => \n array (\n 0 => 'wmlsc',\n ),\n 'application/vnd.webturbo' => \n array (\n 0 => 'wtb',\n ),\n 'application/vnd.wolfram.player' => \n array (\n 0 => 'nbp',\n ),\n 'application/vnd.wordperfect' => \n array (\n 0 => 'wpd',\n ),\n 'application/vnd.wqd' => \n array (\n 0 => 'wqd',\n ),\n 'application/vnd.wt.stf' => \n array (\n 0 => 'stf',\n ),\n 'application/vnd.xara' => \n array (\n 0 => 'xar',\n ),\n 'application/vnd.xfdl' => \n array (\n 0 => 'xfdl',\n ),\n 'application/vnd.yamaha.hv-dic' => \n array (\n 0 => 'hvd',\n ),\n 'application/vnd.yamaha.hv-script' => \n array (\n 0 => 'hvs',\n ),\n 'application/vnd.yamaha.hv-voice' => \n array (\n 0 => 'hvp',\n ),\n 'application/vnd.yamaha.openscoreformat' => \n array (\n 0 => 'osf',\n ),\n 'application/vnd.yamaha.openscoreformat.osfpvg+xml' => \n array (\n 0 => 'osfpvg',\n ),\n 'application/vnd.yamaha.smaf-audio' => \n array (\n 0 => 'saf',\n ),\n 'application/vnd.yamaha.smaf-phrase' => \n array (\n 0 => 'spf',\n ),\n 'application/vnd.yellowriver-custom-menu' => \n array (\n 0 => 'cmp',\n ),\n 'application/vnd.zul' => \n array (\n 0 => 'zir',\n 1 => 'zirz',\n ),\n 'application/vnd.zzazz.deck+xml' => \n array (\n 0 => 'zaz',\n ),\n 'application/voicexml+xml' => \n array (\n 0 => 'vxml',\n ),\n 'application/wasm' => \n array (\n 0 => 'wasm',\n ),\n 'application/watcherinfo+xml' => \n array (\n 0 => 'wif',\n ),\n 'application/widget' => \n array (\n 0 => 'wgt',\n ),\n 'application/winhlp' => \n array (\n 0 => 'hlp',\n ),\n 'application/wsdl+xml' => \n array (\n 0 => 'wsdl',\n ),\n 'application/wspolicy+xml' => \n array (\n 0 => 'wspolicy',\n ),\n 'application/x-7z-compressed' => \n array (\n 0 => '7z',\n 1 => '7zip',\n ),\n 'application/x-abiword' => \n array (\n 0 => 'abw',\n ),\n 'application/x-ace-compressed' => \n array (\n 0 => 'ace',\n ),\n 'application/x-apple-diskimage' => \n array (\n 0 => 'dmg',\n ),\n 'application/x-arj' => \n array (\n 0 => 'arj',\n ),\n 'application/x-authorware-bin' => \n array (\n 0 => 'aab',\n 1 => 'x32',\n 2 => 'u32',\n 3 => 'vox',\n ),\n 'application/x-authorware-map' => \n array (\n 0 => 'aam',\n ),\n 'application/x-authorware-seg' => \n array (\n 0 => 'aas',\n ),\n 'application/x-bcpio' => \n array (\n 0 => 'bcpio',\n ),\n 'application/x-bdoc' => \n array (\n 0 => 'bdoc',\n ),\n 'application/x-bittorrent' => \n array (\n 0 => 'torrent',\n ),\n 'application/x-blorb' => \n array (\n 0 => 'blb',\n 1 => 'blorb',\n ),\n 'application/x-bzip' => \n array (\n 0 => 'bz',\n ),\n 'application/x-bzip2' => \n array (\n 0 => 'bz2',\n 1 => 'boz',\n ),\n 'application/x-cbr' => \n array (\n 0 => 'cbr',\n 1 => 'cba',\n 2 => 'cbt',\n 3 => 'cbz',\n 4 => 'cb7',\n ),\n 'application/x-cdlink' => \n array (\n 0 => 'vcd',\n ),\n 'application/x-cfs-compressed' => \n array (\n 0 => 'cfs',\n ),\n 'application/x-chat' => \n array (\n 0 => 'chat',\n ),\n 'application/x-chess-pgn' => \n array (\n 0 => 'pgn',\n ),\n 'application/x-chrome-extension' => \n array (\n 0 => 'crx',\n ),\n 'application/x-cocoa' => \n array (\n 0 => 'cco',\n ),\n 'application/x-conference' => \n array (\n 0 => 'nsc',\n ),\n 'application/x-cpio' => \n array (\n 0 => 'cpio',\n ),\n 'application/x-csh' => \n array (\n 0 => 'csh',\n ),\n 'application/x-debian-package' => \n array (\n 0 => 'deb',\n 1 => 'udeb',\n ),\n 'application/x-dgc-compressed' => \n array (\n 0 => 'dgc',\n ),\n 'application/x-director' => \n array (\n 0 => 'dir',\n 1 => 'dcr',\n 2 => 'dxr',\n 3 => 'cst',\n 4 => 'cct',\n 5 => 'cxt',\n 6 => 'w3d',\n 7 => 'fgd',\n 8 => 'swa',\n ),\n 'application/x-doom' => \n array (\n 0 => 'wad',\n ),\n 'application/x-dtbncx+xml' => \n array (\n 0 => 'ncx',\n ),\n 'application/x-dtbook+xml' => \n array (\n 0 => 'dtb',\n ),\n 'application/x-dtbresource+xml' => \n array (\n 0 => 'res',\n ),\n 'application/x-dvi' => \n array (\n 0 => 'dvi',\n ),\n 'application/x-envoy' => \n array (\n 0 => 'evy',\n ),\n 'application/x-eva' => \n array (\n 0 => 'eva',\n ),\n 'application/x-font-bdf' => \n array (\n 0 => 'bdf',\n ),\n 'application/x-font-ghostscript' => \n array (\n 0 => 'gsf',\n ),\n 'application/x-font-linux-psf' => \n array (\n 0 => 'psf',\n ),\n 'application/x-font-pcf' => \n array (\n 0 => 'pcf',\n ),\n 'application/x-font-snf' => \n array (\n 0 => 'snf',\n ),\n 'application/x-font-type1' => \n array (\n 0 => 'pfa',\n 1 => 'pfb',\n 2 => 'pfm',\n 3 => 'afm',\n ),\n 'application/x-freearc' => \n array (\n 0 => 'arc',\n ),\n 'application/x-futuresplash' => \n array (\n 0 => 'spl',\n ),\n 'application/x-gca-compressed' => \n array (\n 0 => 'gca',\n ),\n 'application/x-glulx' => \n array (\n 0 => 'ulx',\n ),\n 'application/x-gnumeric' => \n array (\n 0 => 'gnumeric',\n ),\n 'application/x-gramps-xml' => \n array (\n 0 => 'gramps',\n ),\n 'application/x-gtar' => \n array (\n 0 => 'gtar',\n ),\n 'application/x-hdf' => \n array (\n 0 => 'hdf',\n ),\n 'application/x-httpd-php' => \n array (\n 0 => 'php',\n 1 => 'php4',\n 2 => 'php3',\n 3 => 'phtml',\n ),\n 'application/x-install-instructions' => \n array (\n 0 => 'install',\n ),\n 'application/x-iso9660-image' => \n array (\n 0 => 'iso',\n ),\n 'application/x-iwork-keynote-sffkey' => \n array (\n 0 => 'key',\n ),\n 'application/x-iwork-numbers-sffnumbers' => \n array (\n 0 => 'numbers',\n ),\n 'application/x-iwork-pages-sffpages' => \n array (\n 0 => 'pages',\n ),\n 'application/x-java-archive-diff' => \n array (\n 0 => 'jardiff',\n ),\n 'application/x-java-jnlp-file' => \n array (\n 0 => 'jnlp',\n ),\n 'application/x-keepass2' => \n array (\n 0 => 'kdbx',\n ),\n 'application/x-latex' => \n array (\n 0 => 'latex',\n ),\n 'application/x-lua-bytecode' => \n array (\n 0 => 'luac',\n ),\n 'application/x-lzh-compressed' => \n array (\n 0 => 'lzh',\n 1 => 'lha',\n ),\n 'application/x-makeself' => \n array (\n 0 => 'run',\n ),\n 'application/x-mie' => \n array (\n 0 => 'mie',\n ),\n 'application/x-mobipocket-ebook' => \n array (\n 0 => 'prc',\n 1 => 'mobi',\n ),\n 'application/x-ms-application' => \n array (\n 0 => 'application',\n ),\n 'application/x-ms-shortcut' => \n array (\n 0 => 'lnk',\n ),\n 'application/x-ms-wmd' => \n array (\n 0 => 'wmd',\n ),\n 'application/x-ms-wmz' => \n array (\n 0 => 'wmz',\n ),\n 'application/x-ms-xbap' => \n array (\n 0 => 'xbap',\n ),\n 'application/x-msaccess' => \n array (\n 0 => 'mdb',\n ),\n 'application/x-msbinder' => \n array (\n 0 => 'obd',\n ),\n 'application/x-mscardfile' => \n array (\n 0 => 'crd',\n ),\n 'application/x-msclip' => \n array (\n 0 => 'clp',\n ),\n 'application/x-msdos-program' => \n array (\n 0 => 'exe',\n ),\n 'application/x-msdownload' => \n array (\n 0 => 'exe',\n 1 => 'dll',\n 2 => 'com',\n 3 => 'bat',\n 4 => 'msi',\n ),\n 'application/x-msmediaview' => \n array (\n 0 => 'mvb',\n 1 => 'm13',\n 2 => 'm14',\n ),\n 'application/x-msmetafile' => \n array (\n 0 => 'wmf',\n 1 => 'wmz',\n 2 => 'emf',\n 3 => 'emz',\n ),\n 'application/x-msmoney' => \n array (\n 0 => 'mny',\n ),\n 'application/x-mspublisher' => \n array (\n 0 => 'pub',\n ),\n 'application/x-msschedule' => \n array (\n 0 => 'scd',\n ),\n 'application/x-msterminal' => \n array (\n 0 => 'trm',\n ),\n 'application/x-mswrite' => \n array (\n 0 => 'wri',\n ),\n 'application/x-netcdf' => \n array (\n 0 => 'nc',\n 1 => 'cdf',\n ),\n 'application/x-ns-proxy-autoconfig' => \n array (\n 0 => 'pac',\n ),\n 'application/x-nzb' => \n array (\n 0 => 'nzb',\n ),\n 'application/x-perl' => \n array (\n 0 => 'pl',\n 1 => 'pm',\n ),\n 'application/x-pilot' => \n array (\n 0 => 'prc',\n 1 => 'pdb',\n ),\n 'application/x-pkcs12' => \n array (\n 0 => 'p12',\n 1 => 'pfx',\n ),\n 'application/x-pkcs7-certificates' => \n array (\n 0 => 'p7b',\n 1 => 'spc',\n ),\n 'application/x-pkcs7-certreqresp' => \n array (\n 0 => 'p7r',\n ),\n 'application/x-rar-compressed' => \n array (\n 0 => 'rar',\n ),\n 'application/x-redhat-package-manager' => \n array (\n 0 => 'rpm',\n ),\n 'application/x-research-info-systems' => \n array (\n 0 => 'ris',\n ),\n 'application/x-sea' => \n array (\n 0 => 'sea',\n ),\n 'application/x-sh' => \n array (\n 0 => 'sh',\n ),\n 'application/x-shar' => \n array (\n 0 => 'shar',\n ),\n 'application/x-shockwave-flash' => \n array (\n 0 => 'swf',\n ),\n 'application/x-silverlight-app' => \n array (\n 0 => 'xap',\n ),\n 'application/x-sql' => \n array (\n 0 => 'sql',\n ),\n 'application/x-stuffit' => \n array (\n 0 => 'sit',\n ),\n 'application/x-stuffitx' => \n array (\n 0 => 'sitx',\n ),\n 'application/x-subrip' => \n array (\n 0 => 'srt',\n ),\n 'application/x-sv4cpio' => \n array (\n 0 => 'sv4cpio',\n ),\n 'application/x-sv4crc' => \n array (\n 0 => 'sv4crc',\n ),\n 'application/x-t3vm-image' => \n array (\n 0 => 't3',\n ),\n 'application/x-tads' => \n array (\n 0 => 'gam',\n ),\n 'application/x-tar' => \n array (\n 0 => 'tar',\n 1 => 'tgz',\n ),\n 'application/x-tcl' => \n array (\n 0 => 'tcl',\n 1 => 'tk',\n ),\n 'application/x-tex' => \n array (\n 0 => 'tex',\n ),\n 'application/x-tex-tfm' => \n array (\n 0 => 'tfm',\n ),\n 'application/x-texinfo' => \n array (\n 0 => 'texinfo',\n 1 => 'texi',\n ),\n 'application/x-tgif' => \n array (\n 0 => 'obj',\n ),\n 'application/x-ustar' => \n array (\n 0 => 'ustar',\n ),\n 'application/x-virtualbox-hdd' => \n array (\n 0 => 'hdd',\n ),\n 'application/x-virtualbox-ova' => \n array (\n 0 => 'ova',\n ),\n 'application/x-virtualbox-ovf' => \n array (\n 0 => 'ovf',\n ),\n 'application/x-virtualbox-vbox' => \n array (\n 0 => 'vbox',\n ),\n 'application/x-virtualbox-vbox-extpack' => \n array (\n 0 => 'vbox-extpack',\n ),\n 'application/x-virtualbox-vdi' => \n array (\n 0 => 'vdi',\n ),\n 'application/x-virtualbox-vhd' => \n array (\n 0 => 'vhd',\n ),\n 'application/x-virtualbox-vmdk' => \n array (\n 0 => 'vmdk',\n ),\n 'application/x-wais-source' => \n array (\n 0 => 'src',\n ),\n 'application/x-web-app-manifest+json' => \n array (\n 0 => 'webapp',\n ),\n 'application/x-x509-ca-cert' => \n array (\n 0 => 'der',\n 1 => 'crt',\n 2 => 'pem',\n ),\n 'application/x-xfig' => \n array (\n 0 => 'fig',\n ),\n 'application/x-xliff+xml' => \n array (\n 0 => 'xlf',\n ),\n 'application/x-xpinstall' => \n array (\n 0 => 'xpi',\n ),\n 'application/x-xz' => \n array (\n 0 => 'xz',\n ),\n 'application/x-zmachine' => \n array (\n 0 => 'z1',\n 1 => 'z2',\n 2 => 'z3',\n 3 => 'z4',\n 4 => 'z5',\n 5 => 'z6',\n 6 => 'z7',\n 7 => 'z8',\n ),\n 'application/xaml+xml' => \n array (\n 0 => 'xaml',\n ),\n 'application/xcap-att+xml' => \n array (\n 0 => 'xav',\n ),\n 'application/xcap-caps+xml' => \n array (\n 0 => 'xca',\n ),\n 'application/xcap-diff+xml' => \n array (\n 0 => 'xdf',\n ),\n 'application/xcap-el+xml' => \n array (\n 0 => 'xel',\n ),\n 'application/xcap-ns+xml' => \n array (\n 0 => 'xns',\n ),\n 'application/xenc+xml' => \n array (\n 0 => 'xenc',\n ),\n 'application/xfdf' => \n array (\n 0 => 'xfdf',\n ),\n 'application/xhtml+xml' => \n array (\n 0 => 'xhtml',\n 1 => 'xht',\n ),\n 'application/xliff+xml' => \n array (\n 0 => 'xlf',\n ),\n 'application/xml' => \n array (\n 0 => 'xml',\n 1 => 'xsl',\n 2 => 'xsd',\n 3 => 'rng',\n ),\n 'application/xml-dtd' => \n array (\n 0 => 'dtd',\n ),\n 'application/xop+xml' => \n array (\n 0 => 'xop',\n ),\n 'application/xproc+xml' => \n array (\n 0 => 'xpl',\n ),\n 'application/xslt+xml' => \n array (\n 0 => 'xsl',\n 1 => 'xslt',\n ),\n 'application/xspf+xml' => \n array (\n 0 => 'xspf',\n ),\n 'application/xv+xml' => \n array (\n 0 => 'mxml',\n 1 => 'xhvml',\n 2 => 'xvml',\n 3 => 'xvm',\n ),\n 'application/yang' => \n array (\n 0 => 'yang',\n ),\n 'application/yin+xml' => \n array (\n 0 => 'yin',\n ),\n 'application/zip' => \n array (\n 0 => 'zip',\n ),\n 'audio/3gpp' => \n array (\n 0 => '3gpp',\n ),\n 'audio/aac' => \n array (\n 0 => 'adts',\n 1 => 'aac',\n ),\n 'audio/adpcm' => \n array (\n 0 => 'adp',\n ),\n 'audio/amr' => \n array (\n 0 => 'amr',\n ),\n 'audio/basic' => \n array (\n 0 => 'au',\n 1 => 'snd',\n ),\n 'audio/midi' => \n array (\n 0 => 'mid',\n 1 => 'midi',\n 2 => 'kar',\n 3 => 'rmi',\n ),\n 'audio/mobile-xmf' => \n array (\n 0 => 'mxmf',\n ),\n 'audio/mp3' => \n array (\n 0 => 'mp3',\n ),\n 'audio/mp4' => \n array (\n 0 => 'm4a',\n 1 => 'mp4a',\n ),\n 'audio/mpeg' => \n array (\n 0 => 'mpga',\n 1 => 'mp2',\n 2 => 'mp2a',\n 3 => 'mp3',\n 4 => 'm2a',\n 5 => 'm3a',\n ),\n 'audio/ogg' => \n array (\n 0 => 'oga',\n 1 => 'ogg',\n 2 => 'spx',\n 3 => 'opus',\n ),\n 'audio/s3m' => \n array (\n 0 => 's3m',\n ),\n 'audio/silk' => \n array (\n 0 => 'sil',\n ),\n 'audio/vnd.dece.audio' => \n array (\n 0 => 'uva',\n 1 => 'uvva',\n ),\n 'audio/vnd.digital-winds' => \n array (\n 0 => 'eol',\n ),\n 'audio/vnd.dra' => \n array (\n 0 => 'dra',\n ),\n 'audio/vnd.dts' => \n array (\n 0 => 'dts',\n ),\n 'audio/vnd.dts.hd' => \n array (\n 0 => 'dtshd',\n ),\n 'audio/vnd.lucent.voice' => \n array (\n 0 => 'lvp',\n ),\n 'audio/vnd.ms-playready.media.pya' => \n array (\n 0 => 'pya',\n ),\n 'audio/vnd.nuera.ecelp4800' => \n array (\n 0 => 'ecelp4800',\n ),\n 'audio/vnd.nuera.ecelp7470' => \n array (\n 0 => 'ecelp7470',\n ),\n 'audio/vnd.nuera.ecelp9600' => \n array (\n 0 => 'ecelp9600',\n ),\n 'audio/vnd.rip' => \n array (\n 0 => 'rip',\n ),\n 'audio/wav' => \n array (\n 0 => 'wav',\n ),\n 'audio/wave' => \n array (\n 0 => 'wav',\n ),\n 'audio/webm' => \n array (\n 0 => 'weba',\n ),\n 'audio/x-aac' => \n array (\n 0 => 'aac',\n ),\n 'audio/x-aiff' => \n array (\n 0 => 'aif',\n 1 => 'aiff',\n 2 => 'aifc',\n ),\n 'audio/x-caf' => \n array (\n 0 => 'caf',\n ),\n 'audio/x-flac' => \n array (\n 0 => 'flac',\n ),\n 'audio/x-m4a' => \n array (\n 0 => 'm4a',\n ),\n 'audio/x-matroska' => \n array (\n 0 => 'mka',\n ),\n 'audio/x-mpegurl' => \n array (\n 0 => 'm3u',\n ),\n 'audio/x-ms-wax' => \n array (\n 0 => 'wax',\n ),\n 'audio/x-ms-wma' => \n array (\n 0 => 'wma',\n ),\n 'audio/x-pn-realaudio' => \n array (\n 0 => 'ram',\n 1 => 'ra',\n 2 => 'rm',\n ),\n 'audio/x-pn-realaudio-plugin' => \n array (\n 0 => 'rmp',\n 1 => 'rpm',\n ),\n 'audio/x-realaudio' => \n array (\n 0 => 'ra',\n ),\n 'audio/x-wav' => \n array (\n 0 => 'wav',\n ),\n 'audio/xm' => \n array (\n 0 => 'xm',\n ),\n 'chemical/x-cdx' => \n array (\n 0 => 'cdx',\n ),\n 'chemical/x-cif' => \n array (\n 0 => 'cif',\n ),\n 'chemical/x-cmdf' => \n array (\n 0 => 'cmdf',\n ),\n 'chemical/x-cml' => \n array (\n 0 => 'cml',\n ),\n 'chemical/x-csml' => \n array (\n 0 => 'csml',\n ),\n 'chemical/x-xyz' => \n array (\n 0 => 'xyz',\n ),\n 'font/collection' => \n array (\n 0 => 'ttc',\n ),\n 'font/otf' => \n array (\n 0 => 'otf',\n ),\n 'font/ttf' => \n array (\n 0 => 'ttf',\n ),\n 'font/woff' => \n array (\n 0 => 'woff',\n ),\n 'font/woff2' => \n array (\n 0 => 'woff2',\n ),\n 'image/aces' => \n array (\n 0 => 'exr',\n ),\n 'image/apng' => \n array (\n 0 => 'apng',\n ),\n 'image/avci' => \n array (\n 0 => 'avci',\n ),\n 'image/avcs' => \n array (\n 0 => 'avcs',\n ),\n 'image/avif' => \n array (\n 0 => 'avif',\n ),\n 'image/bmp' => \n array (\n 0 => 'bmp',\n 1 => 'dib',\n ),\n 'image/cgm' => \n array (\n 0 => 'cgm',\n ),\n 'image/dicom-rle' => \n array (\n 0 => 'drle',\n ),\n 'image/dpx' => \n array (\n 0 => 'dpx',\n ),\n 'image/emf' => \n array (\n 0 => 'emf',\n ),\n 'image/fits' => \n array (\n 0 => 'fits',\n ),\n 'image/g3fax' => \n array (\n 0 => 'g3',\n ),\n 'image/gif' => \n array (\n 0 => 'gif',\n ),\n 'image/heic' => \n array (\n 0 => 'heic',\n ),\n 'image/heic-sequence' => \n array (\n 0 => 'heics',\n ),\n 'image/heif' => \n array (\n 0 => 'heif',\n ),\n 'image/heif-sequence' => \n array (\n 0 => 'heifs',\n ),\n 'image/hej2k' => \n array (\n 0 => 'hej2',\n ),\n 'image/hsj2' => \n array (\n 0 => 'hsj2',\n ),\n 'image/ief' => \n array (\n 0 => 'ief',\n ),\n 'image/jls' => \n array (\n 0 => 'jls',\n ),\n 'image/jp2' => \n array (\n 0 => 'jp2',\n 1 => 'jpg2',\n ),\n 'image/jpeg' => \n array (\n 0 => 'jpeg',\n 1 => 'jpg',\n 2 => 'jpe',\n ),\n 'image/jph' => \n array (\n 0 => 'jph',\n ),\n 'image/jphc' => \n array (\n 0 => 'jhc',\n ),\n 'image/jpm' => \n array (\n 0 => 'jpm',\n 1 => 'jpgm',\n ),\n 'image/jpx' => \n array (\n 0 => 'jpx',\n 1 => 'jpf',\n ),\n 'image/jxr' => \n array (\n 0 => 'jxr',\n ),\n 'image/jxra' => \n array (\n 0 => 'jxra',\n ),\n 'image/jxrs' => \n array (\n 0 => 'jxrs',\n ),\n 'image/jxs' => \n array (\n 0 => 'jxs',\n ),\n 'image/jxsc' => \n array (\n 0 => 'jxsc',\n ),\n 'image/jxsi' => \n array (\n 0 => 'jxsi',\n ),\n 'image/jxss' => \n array (\n 0 => 'jxss',\n ),\n 'image/ktx' => \n array (\n 0 => 'ktx',\n ),\n 'image/ktx2' => \n array (\n 0 => 'ktx2',\n ),\n 'image/png' => \n array (\n 0 => 'png',\n ),\n 'image/prs.btif' => \n array (\n 0 => 'btif',\n 1 => 'btf',\n ),\n 'image/prs.pti' => \n array (\n 0 => 'pti',\n ),\n 'image/sgi' => \n array (\n 0 => 'sgi',\n ),\n 'image/svg+xml' => \n array (\n 0 => 'svg',\n 1 => 'svgz',\n ),\n 'image/t38' => \n array (\n 0 => 't38',\n ),\n 'image/tiff' => \n array (\n 0 => 'tif',\n 1 => 'tiff',\n ),\n 'image/tiff-fx' => \n array (\n 0 => 'tfx',\n ),\n 'image/vnd.adobe.photoshop' => \n array (\n 0 => 'psd',\n ),\n 'image/vnd.airzip.accelerator.azv' => \n array (\n 0 => 'azv',\n ),\n 'image/vnd.dece.graphic' => \n array (\n 0 => 'uvi',\n 1 => 'uvvi',\n 2 => 'uvg',\n 3 => 'uvvg',\n ),\n 'image/vnd.djvu' => \n array (\n 0 => 'djvu',\n 1 => 'djv',\n ),\n 'image/vnd.dvb.subtitle' => \n array (\n 0 => 'sub',\n ),\n 'image/vnd.dwg' => \n array (\n 0 => 'dwg',\n ),\n 'image/vnd.dxf' => \n array (\n 0 => 'dxf',\n ),\n 'image/vnd.fastbidsheet' => \n array (\n 0 => 'fbs',\n ),\n 'image/vnd.fpx' => \n array (\n 0 => 'fpx',\n ),\n 'image/vnd.fst' => \n array (\n 0 => 'fst',\n ),\n 'image/vnd.fujixerox.edmics-mmr' => \n array (\n 0 => 'mmr',\n ),\n 'image/vnd.fujixerox.edmics-rlc' => \n array (\n 0 => 'rlc',\n ),\n 'image/vnd.microsoft.icon' => \n array (\n 0 => 'ico',\n ),\n 'image/vnd.ms-dds' => \n array (\n 0 => 'dds',\n ),\n 'image/vnd.ms-modi' => \n array (\n 0 => 'mdi',\n ),\n 'image/vnd.ms-photo' => \n array (\n 0 => 'wdp',\n ),\n 'image/vnd.net-fpx' => \n array (\n 0 => 'npx',\n ),\n 'image/vnd.pco.b16' => \n array (\n 0 => 'b16',\n ),\n 'image/vnd.tencent.tap' => \n array (\n 0 => 'tap',\n ),\n 'image/vnd.valve.source.texture' => \n array (\n 0 => 'vtf',\n ),\n 'image/vnd.wap.wbmp' => \n array (\n 0 => 'wbmp',\n ),\n 'image/vnd.xiff' => \n array (\n 0 => 'xif',\n ),\n 'image/vnd.zbrush.pcx' => \n array (\n 0 => 'pcx',\n ),\n 'image/webp' => \n array (\n 0 => 'webp',\n ),\n 'image/wmf' => \n array (\n 0 => 'wmf',\n ),\n 'image/x-3ds' => \n array (\n 0 => '3ds',\n ),\n 'image/x-cmu-raster' => \n array (\n 0 => 'ras',\n ),\n 'image/x-cmx' => \n array (\n 0 => 'cmx',\n ),\n 'image/x-freehand' => \n array (\n 0 => 'fh',\n 1 => 'fhc',\n 2 => 'fh4',\n 3 => 'fh5',\n 4 => 'fh7',\n ),\n 'image/x-icon' => \n array (\n 0 => 'ico',\n ),\n 'image/x-jng' => \n array (\n 0 => 'jng',\n ),\n 'image/x-mrsid-image' => \n array (\n 0 => 'sid',\n ),\n 'image/x-ms-bmp' => \n array (\n 0 => 'bmp',\n ),\n 'image/x-pcx' => \n array (\n 0 => 'pcx',\n ),\n 'image/x-pict' => \n array (\n 0 => 'pic',\n 1 => 'pct',\n ),\n 'image/x-portable-anymap' => \n array (\n 0 => 'pnm',\n ),\n 'image/x-portable-bitmap' => \n array (\n 0 => 'pbm',\n ),\n 'image/x-portable-graymap' => \n array (\n 0 => 'pgm',\n ),\n 'image/x-portable-pixmap' => \n array (\n 0 => 'ppm',\n ),\n 'image/x-rgb' => \n array (\n 0 => 'rgb',\n ),\n 'image/x-tga' => \n array (\n 0 => 'tga',\n ),\n 'image/x-xbitmap' => \n array (\n 0 => 'xbm',\n ),\n 'image/x-xpixmap' => \n array (\n 0 => 'xpm',\n ),\n 'image/x-xwindowdump' => \n array (\n 0 => 'xwd',\n ),\n 'message/disposition-notification' => \n array (\n 0 => 'disposition-notification',\n ),\n 'message/global' => \n array (\n 0 => 'u8msg',\n ),\n 'message/global-delivery-status' => \n array (\n 0 => 'u8dsn',\n ),\n 'message/global-disposition-notification' => \n array (\n 0 => 'u8mdn',\n ),\n 'message/global-headers' => \n array (\n 0 => 'u8hdr',\n ),\n 'message/rfc822' => \n array (\n 0 => 'eml',\n 1 => 'mime',\n ),\n 'message/vnd.wfa.wsc' => \n array (\n 0 => 'wsc',\n ),\n 'model/3mf' => \n array (\n 0 => '3mf',\n ),\n 'model/gltf+json' => \n array (\n 0 => 'gltf',\n ),\n 'model/gltf-binary' => \n array (\n 0 => 'glb',\n ),\n 'model/iges' => \n array (\n 0 => 'igs',\n 1 => 'iges',\n ),\n 'model/jt' => \n array (\n 0 => 'jt',\n ),\n 'model/mesh' => \n array (\n 0 => 'msh',\n 1 => 'mesh',\n 2 => 'silo',\n ),\n 'model/mtl' => \n array (\n 0 => 'mtl',\n ),\n 'model/obj' => \n array (\n 0 => 'obj',\n ),\n 'model/prc' => \n array (\n 0 => 'prc',\n ),\n 'model/step+xml' => \n array (\n 0 => 'stpx',\n ),\n 'model/step+zip' => \n array (\n 0 => 'stpz',\n ),\n 'model/step-xml+zip' => \n array (\n 0 => 'stpxz',\n ),\n 'model/stl' => \n array (\n 0 => 'stl',\n ),\n 'model/u3d' => \n array (\n 0 => 'u3d',\n ),\n 'model/vnd.cld' => \n array (\n 0 => 'cld',\n ),\n 'model/vnd.collada+xml' => \n array (\n 0 => 'dae',\n ),\n 'model/vnd.dwf' => \n array (\n 0 => 'dwf',\n ),\n 'model/vnd.gdl' => \n array (\n 0 => 'gdl',\n ),\n 'model/vnd.gtw' => \n array (\n 0 => 'gtw',\n ),\n 'model/vnd.mts' => \n array (\n 0 => 'mts',\n ),\n 'model/vnd.opengex' => \n array (\n 0 => 'ogex',\n ),\n 'model/vnd.parasolid.transmit.binary' => \n array (\n 0 => 'x_b',\n ),\n 'model/vnd.parasolid.transmit.text' => \n array (\n 0 => 'x_t',\n ),\n 'model/vnd.pytha.pyox' => \n array (\n 0 => 'pyo',\n 1 => 'pyox',\n ),\n 'model/vnd.sap.vds' => \n array (\n 0 => 'vds',\n ),\n 'model/vnd.usda' => \n array (\n 0 => 'usda',\n ),\n 'model/vnd.usdz+zip' => \n array (\n 0 => 'usdz',\n ),\n 'model/vnd.valve.source.compiled-map' => \n array (\n 0 => 'bsp',\n ),\n 'model/vnd.vtu' => \n array (\n 0 => 'vtu',\n ),\n 'model/vrml' => \n array (\n 0 => 'wrl',\n 1 => 'vrml',\n ),\n 'model/x3d+binary' => \n array (\n 0 => 'x3db',\n 1 => 'x3dbz',\n ),\n 'model/x3d+fastinfoset' => \n array (\n 0 => 'x3db',\n ),\n 'model/x3d+vrml' => \n array (\n 0 => 'x3dv',\n 1 => 'x3dvz',\n ),\n 'model/x3d+xml' => \n array (\n 0 => 'x3d',\n 1 => 'x3dz',\n ),\n 'model/x3d-vrml' => \n array (\n 0 => 'x3dv',\n ),\n 'text/cache-manifest' => \n array (\n 0 => 'appcache',\n 1 => 'manifest',\n ),\n 'text/calendar' => \n array (\n 0 => 'ics',\n 1 => 'ifb',\n ),\n 'text/coffeescript' => \n array (\n 0 => 'coffee',\n 1 => 'litcoffee',\n ),\n 'text/css' => \n array (\n 0 => 'css',\n ),\n 'text/csv' => \n array (\n 0 => 'csv',\n ),\n 'text/html' => \n array (\n 0 => 'html',\n 1 => 'htm',\n 2 => 'shtml',\n ),\n 'text/jade' => \n array (\n 0 => 'jade',\n ),\n 'text/javascript' => \n array (\n 0 => 'js',\n 1 => 'mjs',\n ),\n 'text/jsx' => \n array (\n 0 => 'jsx',\n ),\n 'text/less' => \n array (\n 0 => 'less',\n ),\n 'text/markdown' => \n array (\n 0 => 'md',\n 1 => 'markdown',\n ),\n 'text/mathml' => \n array (\n 0 => 'mml',\n ),\n 'text/mdx' => \n array (\n 0 => 'mdx',\n ),\n 'text/n3' => \n array (\n 0 => 'n3',\n ),\n 'text/plain' => \n array (\n 0 => 'txt',\n 1 => 'text',\n 2 => 'conf',\n 3 => 'def',\n 4 => 'list',\n 5 => 'log',\n 6 => 'in',\n 7 => 'ini',\n 8 => 'm3u',\n ),\n 'text/prs.lines.tag' => \n array (\n 0 => 'dsc',\n ),\n 'text/richtext' => \n array (\n 0 => 'rtx',\n ),\n 'text/rtf' => \n array (\n 0 => 'rtf',\n ),\n 'text/sgml' => \n array (\n 0 => 'sgml',\n 1 => 'sgm',\n ),\n 'text/shex' => \n array (\n 0 => 'shex',\n ),\n 'text/slim' => \n array (\n 0 => 'slim',\n 1 => 'slm',\n ),\n 'text/spdx' => \n array (\n 0 => 'spdx',\n ),\n 'text/stylus' => \n array (\n 0 => 'stylus',\n 1 => 'styl',\n ),\n 'text/tab-separated-values' => \n array (\n 0 => 'tsv',\n ),\n 'text/troff' => \n array (\n 0 => 't',\n 1 => 'tr',\n 2 => 'roff',\n 3 => 'man',\n 4 => 'me',\n 5 => 'ms',\n ),\n 'text/turtle' => \n array (\n 0 => 'ttl',\n ),\n 'text/uri-list' => \n array (\n 0 => 'uri',\n 1 => 'uris',\n 2 => 'urls',\n ),\n 'text/vcard' => \n array (\n 0 => 'vcard',\n ),\n 'text/vnd.curl' => \n array (\n 0 => 'curl',\n ),\n 'text/vnd.curl.dcurl' => \n array (\n 0 => 'dcurl',\n ),\n 'text/vnd.curl.mcurl' => \n array (\n 0 => 'mcurl',\n ),\n 'text/vnd.curl.scurl' => \n array (\n 0 => 'scurl',\n ),\n 'text/vnd.dvb.subtitle' => \n array (\n 0 => 'sub',\n ),\n 'text/vnd.familysearch.gedcom' => \n array (\n 0 => 'ged',\n ),\n 'text/vnd.fly' => \n array (\n 0 => 'fly',\n ),\n 'text/vnd.fmi.flexstor' => \n array (\n 0 => 'flx',\n ),\n 'text/vnd.graphviz' => \n array (\n 0 => 'gv',\n ),\n 'text/vnd.in3d.3dml' => \n array (\n 0 => '3dml',\n ),\n 'text/vnd.in3d.spot' => \n array (\n 0 => 'spot',\n ),\n 'text/vnd.sun.j2me.app-descriptor' => \n array (\n 0 => 'jad',\n ),\n 'text/vnd.wap.wml' => \n array (\n 0 => 'wml',\n ),\n 'text/vnd.wap.wmlscript' => \n array (\n 0 => 'wmls',\n ),\n 'text/vtt' => \n array (\n 0 => 'vtt',\n ),\n 'text/wgsl' => \n array (\n 0 => 'wgsl',\n ),\n 'text/x-asm' => \n array (\n 0 => 's',\n 1 => 'asm',\n ),\n 'text/x-c' => \n array (\n 0 => 'c',\n 1 => 'cc',\n 2 => 'cxx',\n 3 => 'cpp',\n 4 => 'h',\n 5 => 'hh',\n 6 => 'dic',\n ),\n 'text/x-component' => \n array (\n 0 => 'htc',\n ),\n 'text/x-fortran' => \n array (\n 0 => 'f',\n 1 => 'for',\n 2 => 'f77',\n 3 => 'f90',\n ),\n 'text/x-handlebars-template' => \n array (\n 0 => 'hbs',\n ),\n 'text/x-java-source' => \n array (\n 0 => 'java',\n ),\n 'text/x-lua' => \n array (\n 0 => 'lua',\n ),\n 'text/x-markdown' => \n array (\n 0 => 'mkd',\n ),\n 'text/x-nfo' => \n array (\n 0 => 'nfo',\n ),\n 'text/x-opml' => \n array (\n 0 => 'opml',\n ),\n 'text/x-org' => \n array (\n 0 => 'org',\n ),\n 'text/x-pascal' => \n array (\n 0 => 'p',\n 1 => 'pas',\n ),\n 'text/x-processing' => \n array (\n 0 => 'pde',\n ),\n 'text/x-sass' => \n array (\n 0 => 'sass',\n ),\n 'text/x-scss' => \n array (\n 0 => 'scss',\n ),\n 'text/x-setext' => \n array (\n 0 => 'etx',\n ),\n 'text/x-sfv' => \n array (\n 0 => 'sfv',\n ),\n 'text/x-suse-ymp' => \n array (\n 0 => 'ymp',\n ),\n 'text/x-uuencode' => \n array (\n 0 => 'uu',\n ),\n 'text/x-vcalendar' => \n array (\n 0 => 'vcs',\n ),\n 'text/x-vcard' => \n array (\n 0 => 'vcf',\n ),\n 'text/xml' => \n array (\n 0 => 'xml',\n ),\n 'text/yaml' => \n array (\n 0 => 'yaml',\n 1 => 'yml',\n ),\n 'video/3gpp' => \n array (\n 0 => '3gp',\n 1 => '3gpp',\n ),\n 'video/3gpp2' => \n array (\n 0 => '3g2',\n ),\n 'video/h261' => \n array (\n 0 => 'h261',\n ),\n 'video/h263' => \n array (\n 0 => 'h263',\n ),\n 'video/h264' => \n array (\n 0 => 'h264',\n ),\n 'video/iso.segment' => \n array (\n 0 => 'm4s',\n ),\n 'video/jpeg' => \n array (\n 0 => 'jpgv',\n ),\n 'video/jpm' => \n array (\n 0 => 'jpm',\n 1 => 'jpgm',\n ),\n 'video/mj2' => \n array (\n 0 => 'mj2',\n 1 => 'mjp2',\n ),\n 'video/mp2t' => \n array (\n 0 => 'ts',\n ),\n 'video/mp4' => \n array (\n 0 => 'mp4',\n 1 => 'mp4v',\n 2 => 'mpg4',\n 3 => 'f4v',\n ),\n 'video/mpeg' => \n array (\n 0 => 'mpeg',\n 1 => 'mpg',\n 2 => 'mpe',\n 3 => 'm1v',\n 4 => 'm2v',\n ),\n 'video/ogg' => \n array (\n 0 => 'ogv',\n ),\n 'video/quicktime' => \n array (\n 0 => 'qt',\n 1 => 'mov',\n ),\n 'video/vnd.dece.hd' => \n array (\n 0 => 'uvh',\n 1 => 'uvvh',\n ),\n 'video/vnd.dece.mobile' => \n array (\n 0 => 'uvm',\n 1 => 'uvvm',\n ),\n 'video/vnd.dece.pd' => \n array (\n 0 => 'uvp',\n 1 => 'uvvp',\n ),\n 'video/vnd.dece.sd' => \n array (\n 0 => 'uvs',\n 1 => 'uvvs',\n ),\n 'video/vnd.dece.video' => \n array (\n 0 => 'uvv',\n 1 => 'uvvv',\n ),\n 'video/vnd.dvb.file' => \n array (\n 0 => 'dvb',\n ),\n 'video/vnd.fvt' => \n array (\n 0 => 'fvt',\n ),\n 'video/vnd.mpegurl' => \n array (\n 0 => 'mxu',\n 1 => 'm4u',\n ),\n 'video/vnd.ms-playready.media.pyv' => \n array (\n 0 => 'pyv',\n ),\n 'video/vnd.uvvu.mp4' => \n array (\n 0 => 'uvu',\n 1 => 'uvvu',\n ),\n 'video/vnd.vivo' => \n array (\n 0 => 'viv',\n ),\n 'video/webm' => \n array (\n 0 => 'webm',\n ),\n 'video/x-f4v' => \n array (\n 0 => 'f4v',\n ),\n 'video/x-fli' => \n array (\n 0 => 'fli',\n ),\n 'video/x-flv' => \n array (\n 0 => 'flv',\n ),\n 'video/x-m4v' => \n array (\n 0 => 'm4v',\n ),\n 'video/x-matroska' => \n array (\n 0 => 'mkv',\n 1 => 'mk3d',\n 2 => 'mks',\n ),\n 'video/x-mng' => \n array (\n 0 => 'mng',\n ),\n 'video/x-ms-asf' => \n array (\n 0 => 'asf',\n 1 => 'asx',\n ),\n 'video/x-ms-vob' => \n array (\n 0 => 'vob',\n ),\n 'video/x-ms-wm' => \n array (\n 0 => 'wm',\n ),\n 'video/x-ms-wmv' => \n array (\n 0 => 'wmv',\n ),\n 'video/x-ms-wmx' => \n array (\n 0 => 'wmx',\n ),\n 'video/x-ms-wvx' => \n array (\n 0 => 'wvx',\n ),\n 'video/x-msvideo' => \n array (\n 0 => 'avi',\n ),\n 'video/x-sgi-movie' => \n array (\n 0 => 'movie',\n ),\n 'video/x-smv' => \n array (\n 0 => 'smv',\n ),\n 'x-conference/x-cooltalk' => \n array (\n 0 => 'ice',\n ),\n 'application/x-photoshop' => \n array (\n 0 => 'psd',\n ),\n 'application/smil' => \n array (\n 0 => 'smi',\n 1 => 'smil',\n ),\n 'application/powerpoint' => \n array (\n 0 => 'ppt',\n ),\n 'application/vnd.ms-powerpoint.addin.macroEnabled.12' => \n array (\n 0 => 'ppam',\n ),\n 'application/vnd.ms-powerpoint.presentation.macroEnabled.12' => \n array (\n 0 => 'pptm',\n 1 => 'potm',\n ),\n 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12' => \n array (\n 0 => 'ppsm',\n ),\n 'application/wbxml' => \n array (\n 0 => 'wbxml',\n ),\n 'application/wmlc' => \n array (\n 0 => 'wmlc',\n ),\n 'application/x-httpd-php-source' => \n array (\n 0 => 'phps',\n ),\n 'application/x-compress' => \n array (\n 0 => 'z',\n ),\n 'application/x-rar' => \n array (\n 0 => 'rar',\n ),\n 'video/vnd.rn-realvideo' => \n array (\n 0 => 'rv',\n ),\n 'application/vnd.ms-word.template.macroEnabled.12' => \n array (\n 0 => 'docm',\n 1 => 'dotm',\n ),\n 'application/vnd.ms-excel.sheet.macroEnabled.12' => \n array (\n 0 => 'xlsm',\n ),\n 'application/vnd.ms-excel.template.macroEnabled.12' => \n array (\n 0 => 'xltm',\n ),\n 'application/vnd.ms-excel.addin.macroEnabled.12' => \n array (\n 0 => 'xlam',\n ),\n 'application/vnd.ms-excel.sheet.binary.macroEnabled.12' => \n array (\n 0 => 'xlsb',\n ),\n 'application/excel' => \n array (\n 0 => 'xl',\n ),\n 'application/x-x509-user-cert' => \n array (\n 0 => 'pem',\n ),\n 'application/x-pkcs10' => \n array (\n 0 => 'p10',\n ),\n 'application/x-pkcs7-signature' => \n array (\n 0 => 'p7a',\n ),\n 'application/pgp' => \n array (\n 0 => 'pgp',\n ),\n 'application/gpg-keys' => \n array (\n 0 => 'gpg',\n ),\n 'application/x-pkcs7' => \n array (\n 0 => 'rsa',\n ),\n 'video/3gp' => \n array (\n 0 => '3gp',\n ),\n 'audio/acc' => \n array (\n 0 => 'aac',\n ),\n 'application/vnd.mpegurl' => \n array (\n 0 => 'm4u',\n ),\n 'application/videolan' => \n array (\n 0 => 'vlc',\n ),\n 'audio/x-au' => \n array (\n 0 => 'au',\n ),\n 'audio/ac3' => \n array (\n 0 => 'ac3',\n ),\n 'text/x-scriptzsh' => \n array (\n 0 => 'zsh',\n ),\n 'application/cdr' => \n array (\n 0 => 'cdr',\n ),\n 'application/STEP' => \n array (\n 0 => 'step',\n 1 => 'stp',\n ),\n 'application/x-ndjson' => \n array (\n 0 => 'ndjson',\n ),\n 'application/braille' => \n array (\n 0 => 'brf',\n ),\n);

Methods

1. lookupMimeType

Declaration

public function lookupMimeType(
    string $extension
) : string
{
}

Description

Loock up mime type

Parameters

$extension

Extension

Return

string
2. lookupExtension

Declaration

public function lookupExtension(
    string $mimetype
) : string
{
}

Description

Look up extension

Parameters

$mimetype

MIME Type

Return

string
3. lookupAllExtensions

Declaration

public function lookupAllExtensions(
    string $mimetype
) : string[]
{
}

Description

Look up all extensions

Parameters

$mimetype

MIME Type

Return

string[]

MagicObject\Database\PicoDatabase

Declaration

class PicoDatabase { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

PicoDatabase provides an interface for database interactions using PDO.

This class manages database connections, query execution, and transactions. It supports callbacks for query execution and debugging, allowing developers to handle SQL commands and responses effectively.

Features include:

  • Establishing and managing a database connection.
  • Executing various SQL commands (INSERT, UPDATE, DELETE, etc.).
  • Transaction management with commit and rollback functionality.
  • Fetching results in different formats (array, object, etc.).
  • Generating unique IDs and retrieving the last inserted ID.

    Example:

    <?php
    $db = new PicoDatabase($credentials);
    $db->connect();
    $result = $db->fetch("SELECT * FROM users WHERE id = 1");

Constants

const QUERY_INSERT = "insert";
const QUERY_UPDATE = "update";
const QUERY_DELETE = "delete";
const QUERY_TRANSACTION = "transaction";
const DATABASE_NONECTION_IS_NULL = "Database connection is null";

Properties

1. databaseCredentials

Declaration

protected SecretObject $databaseCredentials;

Description

Database credential.

2. connected

Declaration

protected bool $connected = false;

Description

Indicates whether the database is connected or not.

3. autocommit

Declaration

protected bool $autocommit = true;

Description

Autocommit setting.

4. databaseConnection

Declaration

protected PDO $databaseConnection;

Description

Database connection.

5. databaseType

Declaration

protected string $databaseType = '';

Description

Database type.

6. callbackExecuteQuery

Declaration

protected callable $callbackExecuteQuery;

Description

Callback function when executing queries that modify data.

7. callbackDebugQuery

Declaration

protected callable $callbackDebugQuery;

Description

Callback function when executing any query.

Methods

1. fromPdo

Declaration

public static function fromPdo(
    PDO $pdo
) : PicoDatabase
{
}

Description

Creates a PicoDatabase instance from an existing PDO connection.

This static method accepts a PDO connection object, initializes a new PicoDatabase instance, and sets up the database connection and type. It also marks the database as connected and returns the configured PicoDatabase object.

Parameters

$pdo

The PDO connection object representing an active connection to the database.

Return

PicoDatabase

Returns a new instance of the PicoDatabase class,

2. getDatabaseCredentialsFromPdo

Declaration

private static function getDatabaseCredentialsFromPdo(
    PDO $pdo,
    string $driver,
    string $dbType
) : SecretObject
{
}

Description

Retrieves detailed information about a PDO database connection.

This method extracts and organizes connection details, including:

  • Database driver (e.g., 'mysql', 'pgsql', 'sqlite').
  • Host and port (if available).
  • Database name (derived from the connection DSN).
  • Schema (for applicable databases like PostgreSQL).
  • Time zone (calculated from the database offset or default PHP time zone).

    The extraction process dynamically adapts to the type of database (e.g., MySQL, PostgreSQL, SQLite). For PostgreSQL, the schema is determined using a database query. Time zone information is calculated by converting the database offset to a corresponding PHP time zone where possible.

    The resulting connection details are encapsulated in a SecretObject for secure handling and organized access.

Parameters

$pdo

The PDO connection object.

$driver

The name of the database driver (e.g., 'mysql', 'pgsql', 'sqlite').

$dbType

The database type constant as defined in PicoDatabaseType.

Return

SecretObject

A SecretObject instance containing the following properties:

Throws

PDOException

If an error occurs during database interaction, such as a query failure or

3. getTimeZoneOffset

Declaration

private static function getTimeZoneOffset(
    PDO $pdo
) : string
{
}

Description

Retrieves the timezone offset from the database.

This function detects the database type (MySQL, MariaDB, or PostgreSQL) from the given PDO connection and executes the appropriate query to determine the timezone offset from UTC. It returns the offset as a string in the format "+HH:MM" or "-HH:MM". If the database type is unsupported or an error occurs, it defaults to "00:00".

Parameters

$pdo

The PDO connection object.

Return

string

The timezone offset as a string (e.g., "+08:00", "-05:30"), or "00:00" on failure.

4. convertOffsetToTimeZone

Declaration

private static function convertOffsetToTimeZone(
    string $offset
) : string
{
}

Description

Converts a timezone offset string to a corresponding PHP timezone name.

This method takes a timezone offset string (e.g., "+08:00" or "-05:30") and computes the total offset in seconds. It then attempts to map the offset to a standard PHP timezone name. If no matching timezone is found, it falls back to returning a UTC-based timezone string in the same offset format.

Examples:

  • Input: "+07:00" -> Output: "Asia/Jakarta" (if mapping exists).
  • Input: "-05:30" -> Output: "UTC-05:30" (fallback if no mapping exists).

Parameters

$offset

The timezone offset string (e.g., "+07:00", "-05:30").

Return

string

The corresponding PHP timezone name, or a fallback UTC offset string (e.g., "UTC+07:00").

5. __construct

Declaration

public function __construct(
    SecretObject $databaseCredentials,
    callable|null $callbackExecuteQuery = null,
    callable|null $callbackDebugQuery = null
)
{
}

Description

Constructor to initialize the PicoDatabase object.

Parameters

$databaseCredentials

Database credentials.

$callbackExecuteQuery

Callback for executing modifying queries. Parameter 1 is SQL, parameter 2 is one of query type (PicoDatabase::QUERY_INSERT, PicoDatabase::QUERY_UPDATE, PicoDatabase::QUERY_DELETE, PicoDatabase::QUERY_TRANSACTION).

$callbackDebugQuery

Callback for debugging queries. Parameter 1 is SQL.

6. connect

Declaration

public function connect(
    bool $withDatabase = true
) : bool
{
}

Description

Connect to the database.

Establishes a connection to the specified database type. Optionally selects a database if the connection is to an RDMS and the flag is set.

Parameters

$withDatabase

Flag to select the database when connected (default is true).

Return

bool

True if the connection is successful, false if it fails.

7. connectSqlite

Declaration

private function connectSqlite() : bool
{
}

Description

Connect to SQLite database.

Establishes a connection to an SQLite database using the specified file path in the credentials. Throws an exception if the database path is not set or is empty.

Return

bool

True if the connection is successful, false if it fails.

Throws

InvalidDatabaseConfiguration

If the database path is empty.

PDOException

If the connection fails with an error.

8. connectRDMS

Declaration

private function connectRDMS(
    bool $withDatabase = true
) : bool
{
}

Description

Connect to the RDMS (Relational Database Management System).

Establishes a connection to an RDMS database using the provided credentials. Optionally, a specific database is selected based on the provided flag. This method also configures the time zone, character set, and schema settings (for PostgreSQL) after the connection is established.

  • The time zone is set based on the current offset (date("P")), or a configured value.
  • For PostgreSQL, the client encoding (charset) is set using SET CLIENT_ENCODING, and the schema is set using SET search_path.
  • For MySQL, the time zone and charset are set using SET time_zone and SET NAMES.

Parameters

$withDatabase

Flag to specify whether to select a database upon connection (default is true).

Return

bool

True if the connection is successfully established, false otherwise.

Throws

InvalidDatabaseConfiguration

If the database username is missing from the configuration.

PDOException

If an error occurs during the connection process.

9. connectMySql

Declaration

private function connectMySql(
    string $connectionString,
    string $timeZoneOffset,
    string $charset
) : void
{
}

Description

Establish a connection to a MySQL or MariaDB database.

This method sets up a connection to a MySQL or MariaDB database, configuring the time zone and character set (charset) as needed. It runs initial queries to set the correct time zone and charset, and then establishes a PDO connection to the database.

Parameters

$connectionString

The connection string used to connect to the database.

$timeZoneOffset

The time zone offset to be used in the database session.

$charset

The character set (charset) to be used for the database connection.

Return

void

Throws

PDOException

If there is an error while establishing the connection or executing the initial queries.

10. connectPostgreSql

Declaration

private function connectPostgreSql(
    string $connectionString,
    string $timeZoneOffset,
    string $charset
) : void
{
}

Description

Establish a connection to a PostgreSQL database.

This method sets up a connection to a PostgreSQL database, configuring the time zone, character set (charset), and schema (search path) as needed. It runs initial queries to set the correct time zone, charset, and schema for the session, and then establishes a PDO connection to the database.

Parameters

$connectionString

The connection string used to connect to the PostgreSQL database.

$timeZoneOffset

The time zone offset to be used in the database session.

$charset

The character set (charset) to be used for the PostgreSQL connection.

Return

void

Throws

PDOException

If there is an error while establishing the connection or executing the initial queries.

11. connectSqlServer

Declaration

private function connectSqlServer(
    string $connectionString
) : void
{
}

Description

Establish a connection to a SQL Server database.

This method sets up a connection to a SQL Server database and then establishes a PDO connection to the database.

Parameters

$connectionString

The connection string used to connect to the SQL Server database.

Return

void

Throws

PDOException

If there is an error while establishing the connection or executing the initial queries.

12. getDbType

Declaration

private static function getDbType(
    string $databaseType
) : string
{
}

Description

Determine the database type from a string.

This method evaluates the provided string to identify common database types such as SQLite, PostgreSQL, MariaDB, MySQL, and SQL Server. It returns the corresponding constant from the PicoDatabaseType class. If the provided database type is not supported, it throws an UnsupportedDatabaseException.

Parameters

$databaseType

The database type string (e.g., 'SQLite', 'PostgreSQL', 'MariaDB', 'MySQL', 'SQLServer').

Return

string

The corresponding PicoDatabaseType constant, one of:

Throws

UnsupportedDatabaseException

If the database type is unsupported.

13. getDbDriver

Declaration

private function getDbDriver(
    string $databaseType
) : string
{
}

Description

Determines the database driver based on the provided database type.

This function takes a string representing the database type and returns the corresponding database driver constant from the PicoDatabaseType class. It supports SQLite, PostgreSQL, MySQL/MariaDB, and SQL Server types.

Parameters

$databaseType

The type of the database (e.g., 'sqlite', 'postgres', 'pgsql', 'mysql', 'mariadb', 'sqlsrv').

Return

string

The corresponding database driver constant, one of:

14. constructConnectionString

Declaration

private function constructConnectionString(
    bool $withDatabase = true
) : string
{
}

Description

Create a connection string.

Parameters

$withDatabase

Flag to select the database when connected.

Return

string

The constructed connection string.

Throws

InvalidDatabaseConfiguration

If database configuration is invalid.

15. disconnect

Declaration

public function disconnect() : self
{
}

Description

Disconnect from the database.

This method sets the database connection to null, effectively closing the connection to the database.

Return

self

Returns the current instance for method chaining.

16. setTimeZoneOffset

Declaration

public function setTimeZoneOffset(
    string $timeZoneOffset
) : self
{
}

Description

Set the time zone offset for the database session.

This method sets the time zone offset for the current session, which can be useful for time-related operations.

Parameters

$timeZoneOffset

The time zone offset to set for the session (e.g., '+00:00', 'Europe/London').

Return

self

Returns the current instance for method chaining.

17. setTimeZone

Declaration

public function setTimeZone(
    string $timeZoneOffset
) : self
{
}

Description

Set the time zone offset for the database session.

This method sets the time zone offset for the current database session. This is useful for ensuring that any time-related operations (such as querying and storing timestamps) are adjusted to the correct time zone. The method generates the appropriate SQL command based on the type of the database (e.g., PostgreSQL, MySQL, etc.) and executes it to apply the time zone setting.

Parameters

$timeZoneOffset

The time zone offset to set for the session. It can either be a valid UTC offset (e.g., '+00:00')

Return

self

Returns the current instance for method chaining.

18. getTimeZoneOffsetFromString

Declaration

public static function getTimeZoneOffsetFromString(
    string $timezone
) : string
{
}

Description

Converts a timezone name (e.g., 'Asia/Jakarta') to its corresponding UTC offset (e.g., '+07:00' or '-03:00').

This function will return the timezone offset without affecting the current PHP runtime timezone.

Parameters

$timezone

The name of the timezone, e.g., 'Asia/Jakarta'.

Return

string

The UTC offset corresponding to the provided timezone, e.g., '+07:00' or '-03:00'.

19. useDatabase

Declaration

public function useDatabase(
    string $databaseName
) : self
{
}

Description

Switch to a different database.

This method changes the currently active database to the specified one.

Parameters

$databaseName

The name of the database to switch to.

Return

self

Returns the current instance for method chaining.

20. setAudoCommit

Declaration

public function setAudoCommit(
    bool $autocommit
) : bool
{
}

Description

Set autocommit mode for transactions.

This method enables or disables autocommit mode for database transactions. When autocommit is off, you must explicitly call commit() or rollback() to finalize or revert the transaction.

Parameters

$autocommit

Flag indicating whether autocommit should be enabled (true) or disabled (false).

Return

bool

Returns true if the autocommit setting was successfully updated, false otherwise.

21. startTransaction

Declaration

public function startTransaction() : bool
{
}

Description

Start a new database transaction.

This method begins a new transaction, allowing subsequent database operations to be grouped together. The changes made during the transaction are not permanent until the transaction is committed.

Return

bool

Returns true if the transaction was successfully started, false otherwise.

22. commit

Declaration

public function commit() : bool
{
}

Description

Commit the current transaction.

This method commits the transaction, making all changes made during the transaction permanent.

Return

bool

Returns true if the transaction was successfully committed, false otherwise.

23. rollback

Declaration

public function rollback() : bool
{
}

Description

Rollback the current transaction.

This method rolls back the transaction, undoing any changes made during the transaction.

Return

bool

Returns true if the transaction was successfully rolled back, false otherwise.

24. getDatabaseConnection

Declaration

public function getDatabaseConnection() : PDO
{
}

Description

Get the current database connection.

This method returns the active PDO connection object, which can be used for executing queries directly.

Return

PDO

The active PDO connection object representing the connection to the database server.

25. query

Declaration

public function query(
    string $sql,
    array|null $params = null
) : PDOStatement|false
{
}

Description

Execute a SQL query.

This method executes a SQL query with optional parameters and returns the resulting PDO statement object.

Parameters

$sql

The SQL query to execute.

$params

Optional parameters to bind to the query.

Return

PDOStatement|false

Returns a PDOStatement object if the query was executed successfully,

Throws

PDOException

If an error occurs while executing the query.

26. fetch

Declaration

public function fetch(
    string $sql,
    int $tentativeType = 2,
    mixed $defaultValue = null,
    array|null $params = null
) : array|object|stdClass|null
{
}

Description

Fetch a result from the database.

This method executes a query and returns a single result. If no result is found, the default value is returned.

Parameters

$sql

SQL query to be executed.

$tentativeType

The fetch mode to be used (e.g., PDO::FETCH_ASSOC).

$defaultValue

The default value to return if no results are found.

$params

Optional parameters to bind to the SQL query.

Return

array|object|stdClass|null

Returns the fetched result (array, object, or stdClass), or the default value if no results are found.

27. isRecordExists

Declaration

public function isRecordExists(
    string $sql,
    array|null $params = null
) : bool
{
}

Description

Check if a record exists in the database.

This method executes a query and checks if any record is returned.

Parameters

$sql

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

Return

bool

Returns true if the record exists, false otherwise.

Throws

NullPointerException

If the database connection is null.

28. fetchAll

Declaration

public function fetchAll(
    string $sql,
    int $tentativeType = 2,
    mixed $defaultValue = null,
    array|null $params = null
) : array|null
{
}

Description

Fetch all results from the database.

This method executes a query and returns all matching results. If no results are found, the default value is returned.

Parameters

$sql

SQL query to be executed.

$tentativeType

The fetch mode to be used (e.g., PDO::FETCH_ASSOC).

$defaultValue

The default value to return if no results are found.

$params

Optional parameters to bind to the SQL query.

Return

array|null

Returns an array of results or the default value if no results are found.

29. execute

Declaration

public function execute(
    string $sql,
    array|null $params = null
) : PDOStatement|false
{
}

Description

Execute a SQL query without returning any results.

This method executes a query without expecting any result, typically used for non-SELECT queries (INSERT, UPDATE, DELETE).

Parameters

$sql

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

Return

PDOStatement|false

Returns the PDOStatement object if successful, or false on failure.

Throws

NullPointerException

If the database connection is null.

PDOException

If an error occurs while executing the query.

30. executeQuery

Declaration

public function executeQuery(
    string $sql,
    array|null $params = null
) : PDOStatement|false
{
}

Description

Execute a SQL query and return the statement object.

This method executes a query and returns the PDOStatement object, which can be used to fetch results or retrieve row count.

Parameters

$sql

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

Return

PDOStatement|false

Returns the PDOStatement object if successful, or false on failure.

Throws

NullPointerException

If the database connection is null.

PDOException

If an error occurs while executing the query.

31. executeInsert

Declaration

public function executeInsert(
    string $sql,
    array|null $params = null
) : PDOStatement|false
{
}

Description

Execute an insert query and return the statement.

This method executes an insert query and returns the PDOStatement object.

Parameters

$sql

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

Return

PDOStatement|false

Returns the PDOStatement object if successful, or false on failure.

32. executeUpdate

Declaration

public function executeUpdate(
    string $sql,
    array|null $params = null
) : PDOStatement|false
{
}

Description

Execute an update query and return the statement.

This method executes an update query and returns the PDOStatement object.

Parameters

$sql

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

Return

PDOStatement|false

Returns the PDOStatement object if successful, or false on failure.

33. executeDelete

Declaration

public function executeDelete(
    string $sql,
    array|null $params = null
) : PDOStatement|false
{
}

Description

Execute a delete query and return the statement.

This method executes a delete query and returns the PDOStatement object.

Parameters

$sql

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

Return

PDOStatement|false

Returns the PDOStatement object if successful, or false on failure.

34. executeTransaction

Declaration

public function executeTransaction(
    string $sql,
    array|null $params = null
) : PDOStatement|false
{
}

Description

Execute a transaction query and return the statement.

This method executes a query as part of a transaction and returns the PDOStatement object.

Parameters

$sql

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

Return

PDOStatement|false

Returns the PDOStatement object if successful, or false on failure.

35. executeCallback

Declaration

private function executeCallback(
    string $query,
    array|null $params = null,
    string|null $type = null
)
{
}

Description

Execute a callback query function after executing the query.

This method calls the provided callback function after executing a query.

Parameters

$query

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

$type

Type of the query (e.g., INSERT, UPDATE, DELETE, etc.).

36. executeDebug

Declaration

private function executeDebug(
    string $query,
    array|null $params = null
)
{
}

Description

Execute a debug query function.

This method calls a debug callback function if it is set.

Parameters

$query

SQL query to be executed.

$params

Optional parameters to bind to the SQL query.

37. generateNewId

Declaration

public function generateNewId() : string
{
}

Description

Generate a unique 20-byte ID.

This method generates a unique ID by concatenating a 13-character string from uniqid() with a 6-character random hexadecimal string, ensuring the resulting string is 20 characters in length.

Return

string

A unique 20-byte identifier.

38. lastInsertId

Declaration

public function lastInsertId(
    string|null $name = null
) : string|false
{
}

Description

Get the last inserted ID.

This method retrieves the ID of the last inserted record. Optionally, you can provide a sequence name (e.g., for PostgreSQL) to fetch the last inserted ID from a specific sequence.

Parameters

$name

The sequence name (e.g., PostgreSQL). Default is null.

Return

string|false

Returns the last inserted ID as a string, or false if there was an error.

39. getDatabaseCredentials

Declaration

public function getDatabaseCredentials() : SecretObject
{
}

Description

Get the value of database credentials.

This method returns the object containing the database credentials used to establish the database connection.

Return

SecretObject

The database credentials object.

40. isConnected

Declaration

public function isConnected() : bool
{
}

Description

Check whether the database is connected.

This method returns a boolean value indicating whether the database connection is currently active.

Return

bool

Returns true if connected, false otherwise.

41. getDatabaseType

Declaration

public function getDatabaseType() : string
{
}

Description

Get the type of the database.

This method returns the type of the database that is currently connected. The possible values are constants from the PicoDatabaseType class:

  • PicoDatabaseType::DATABASE_TYPE_MYSQL
  • PicoDatabaseType::DATABASE_TYPE_MARIADB
  • PicoDatabaseType::DATABASE_TYPE_PGSQL
  • PicoDatabaseType::DATABASE_TYPE_SQLITE

Return

string

The type of the database.

42. getDatabaseTimeZone

Declaration

public function getDatabaseTimeZone() : string
{
}

Description

Retrieves the time zone used by the database.

This function calls the getTimeZone() method from the databaseCredentials object to fetch the time zone configured for the database connection.

Return

string

The time zone of the database (e.g., "UTC", "America/New_York").

43. getDatabaseTimeZoneOffset

Declaration

public function getDatabaseTimeZoneOffset() : string
{
}

Description

Retrieves the time zone offset of the database connection.

This function retrieves the time zone offset by calling the static method getTimeZoneOffset() with the databaseConnection as an argument. The offset is returned in seconds from UTC.

Return

string

The time zone offset, typically in hours and minutes (e.g., "+02:00").

44. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

45. getCallbackExecuteQuery

Declaration

public function getCallbackExecuteQuery() : callable|null
{
}

Description

Get the callback function to be executed when modifying data with queries.

This function returns the callback that is invoked when executing queries that modify data (e.g., INSERT, UPDATE, DELETE).

Return

callable|null

The callback function, or null if no callback is set.

46. setCallbackExecuteQuery

Declaration

public function setCallbackExecuteQuery(
    callable|null $callbackExecuteQuery
) : self
{
}

Description

Set the callback function to be executed when modifying data with queries.

This method sets the callback to be invoked when executing queries that modify data (e.g., INSERT, UPDATE, DELETE).

Parameters

$callbackExecuteQuery

The callback function to set, or null to unset the callback.

Return

self

Returns the current instance for method chaining.

47. getCallbackDebugQuery

Declaration

public function getCallbackDebugQuery() : callable|null
{
}

Description

Get the callback function to be executed when executing any query.

This function returns the callback that is invoked for any type of query, whether it's a read (SELECT) or modify (INSERT, UPDATE, DELETE).

Return

callable|null

The callback function, or null if no callback is set.

48. setCallbackDebugQuery

Declaration

public function setCallbackDebugQuery(
    callable|null $callbackDebugQuery
) : self
{
}

Description

Set the callback function to be executed when executing any query.

This method sets the callback to be invoked for any type of query, whether it's a read (SELECT) or modify (INSERT, UPDATE, DELETE).

Parameters

$callbackDebugQuery

The callback function to set, or null to unset the callback.

Return

self

Returns the current instance for method chaining.

MagicObject\Database\PicoDatabaseCredentials

Declaration

class PicoDatabaseCredentials extends MagicObject\SecretObject { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

PicoDatabaseCredentials class

This class encapsulates database credentials and utilizes the SecretObject to encrypt all attributes, ensuring the security of database configuration details from unauthorized access.

It provides getter methods to retrieve database connection parameters such as driver, host, port, username, password, database name, schema, and application time zone.

Example usage:

 <?php
 $credentials = new PicoDatabaseCredentials();
 $credentials->setHost('localhost');
 $credentials->setUsername('user');
 $credentials->setPassword('password');

The attributes are automatically encrypted when set, providing a secure way to handle sensitive information within your application.

Properties

1. driver

Declaration

protected string $driver;

Description

Database driver (e.g., 'mysql', 'pgsql', 'mariadb', 'sqlite').

2. databaseFilePath

Declaration

protected string $databaseFilePath;

Description

Database file path for SQLite.

3. host

Declaration

protected string $host;

Description

Database server host.

4. port

Declaration

protected int $port;

Description

Database server port.

5. username

Declaration

protected string $username;

Description

Database username.

6. password

Declaration

protected string $password;

Description

Database user password.

7. databaseName

Declaration

protected string $databaseName;

Description

Database name.

8. databaseSchema

Declaration

protected string $databaseSchema;

Description

Database schema (default: 'public').

9. timeZone

Declaration

protected string $timeZone;

Description

Application time zone.

10. charset

Declaration

protected string $charset;

Description

Charset

11. _classParams

Declaration

protected array $_classParams = array();

Description

Class parameters.

The property name starts with an underscore to prevent child classes from overriding its value.

12. _nullProperties

Declaration

protected array $_nullProperties = array();

Description

NULL properties.

The property name starts with an underscore to prevent child classes from overriding its value.

MagicObject\Database\PicoDatabaseEntity

Declaration

class PicoDatabaseEntity { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseEntity

Represents a database entity that manages multiple database connections.

Properties

1. databases

Declaration

private PicoDatabase[] $databases = array();

Description

An associative array of databases indexed by entity class name.

2. defaultDatabase

Declaration

private PicoDatabase $defaultDatabase;

Description

Default database connection

Methods

1. add

Declaration

public function add(
    MagicObject $entity,
    PicoDatabase|null $database = null
) : self
{
}

Description

Adds an entity to the database.

Parameters

$entity

The entity to add.

$database

The database to associate with the entity. If null,

Return

self

Returns the current instance for method chaining.

2. getDatabase

Declaration

public function getDatabase(
    MagicObject $entity
) : PicoDatabase|null
{
}

Description

Gets the database associated with an entity.

Parameters

$entity

The entity whose database is to be retrieved.

Return

PicoDatabase|null

Returns the associated database or null if not found.

3. getDefaultDatabase

Declaration

public function getDefaultDatabase() : PicoDatabase
{
}

Description

Get default database connection

Return

PicoDatabase
4. setDefaultDatabase

Declaration

public function setDefaultDatabase(
    PicoDatabase $defaultDatabase
) : self
{
}

Description

Set default database connection

Parameters

$defaultDatabase

Default database connection

Return

self

MagicObject\Database\PicoDatabasePersistence

Declaration

class PicoDatabasePersistence { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Database persistence

Constants

const ANNOTATION_TABLE = "Table";
const ANNOTATION_CACHE = "Cache";
const ANNOTATION_COLUMN = "Column";
const ANNOTATION_JOIN_COLUMN = "JoinColumn";
const ANNOTATION_VAR = "var";
const ANNOTATION_ID = "Id";
const ANNOTATION_GENERATED_VALUE = "GeneratedValue";
const ANNOTATION_NOT_NULL = "NotNull";
const ANNOTATION_DEFAULT_COLUMN = "DefaultColumn";
const ANNOTATION_JSON_FORMAT = "JsonFormat";
const ANNOTATION_PACKAGE = "package";
const SQL_DATE_TIME_FORMAT = "SqlDateTimeFormat";
const KEY_NAME = "name";
const KEY_REFERENCE_COLUMN_NAME = "referenceColumnName";
const KEY_NULL = "null";
const KEY_NOT_NULL = "notnull";
const KEY_NULLABLE = "nullable";
const KEY_INSERTABLE = "insertable";
const KEY_UPDATABLE = "updatable";
const KEY_STRATEGY = "strategy";
const KEY_GENERATOR = "generator";
const KEY_PROPERTY_TYPE = "propertyType";
const KEY_VALUE = "value";
const KEY_TYPE = "type";
const KEY_ENABLE = "enable";
const KEY_ENTITY_OBJECT = "entityObject";
const VALUE_TRUE = "true";
const VALUE_FALSE = "false";
const ORDER_ASC = "asc";
const ORDER_DESC = "desc";
const MESSAGE_NO_PRIMARY_KEY_DEFINED = "No primary key is defined.";
const MESSAGE_NO_RECORD_FOUND = "No records found.";
const MESSAGE_INVALID_FILTER = "Invalid filter";
const SQL_DATETIME_FORMAT = "Y-m-d H:i:s";
const DATE_TIME_FORMAT = "datetimeformat";
const NAMESPACE_SEPARATOR = "\\";
const JOIN_TABLE_SUBFIX = "__jn__";
const MAX_LINE_LENGTH = 80;
const COMMA = ", ";
const COMMA_RETURN = ", \r\n";
const INLINE_TRIM = " \r\n\t ";
const ALWAYS_TRUE = "(1=1)";

Properties

1. database

Declaration

protected PicoDatabase $database;

Description

Database connection

2. object

Declaration

protected MagicObject $object;

Description

Object

3. className

Declaration

protected string $className = '';

Description

Class name

4. flagIncludeNull

Declaration

private boolean $flagIncludeNull = false;

Description

Skip null

5. importedClassList

Declaration

private array $importedClassList = array();

Description

Imported class list

6. processClassList

Declaration

private boolean $processClassList = false;

Description

Flag that class list has been processed or not

7. namespaceName

Declaration

private string $namespaceName = '';

Description

Get namespace of class

8. generatedValue

Declaration

private boolean $generatedValue = false;

Description

Flag that generated value has been added

9. requireDbAutoincrement

Declaration

private boolean $requireDbAutoincrement = false;

Description

Flag that entity require database autoincrement

10. dbAutoinrementCompleted

Declaration

private boolean $dbAutoinrementCompleted = false;

Description

Flag that database autoincrement has been completed

11. tableInfoProp

Declaration

private PicoTableInfo $tableInfoProp;

Description

Table Info

12. entityTable

Declaration

private array $entityTable = array();

Description

Entity table cache

13. joinColumMaps

Declaration

protected PicoJoinMap[] $joinColumMaps = array();

Description

Join map

14. whereIsDefinedFirst

Declaration

protected boolean $whereIsDefinedFirst = false;

Description

Flag that WHERE is defined first

15. whereStr

Declaration

protected string $whereStr;

Description

WHERE saved on previous

16. specification

Declaration

protected PicoSpecification $specification;

Description

Specification

17. pageable

Declaration

protected PicoPageable $pageable;

Description

Pageable

18. sortable

Declaration

protected PicoSortable $sortable;

Description

Sortable

19. joinCache

Declaration

private array $joinCache = array();

Description

Join cache

20. timeZoneOffset

Declaration

private string $timeZoneOffset;

Description

The timezone offset for the current session, in the format '+hh:mm' or '-hh:mm'. This offset represents the time difference between the current session's timezone and UTC.

21. timeZoneOffsetSystem

Declaration

private string $timeZoneOffsetSystem;

Description

The system's timezone offset, representing the offset used by the system's configuration, in the format '+hh:mm' or '-hh:mm'. This offset is typically used when interacting with the system's time settings.

22. timeZone

Declaration

private string $timeZone;

Description

The timezone identifier for the current session, e.g., 'Asia/Jakarta'. This timezone is used for time-related operations within the session.

23. timeZoneSystem

Declaration

private string $timeZoneSystem;

Description

The system's timezone identifier, representing the timezone used by the system, e.g., 'Europe/London'. This timezone is typically used for system-level time settings.

Methods

1. __construct

Declaration

public function __construct(
    PicoDatabase|null $database,
    MagicObject|mixed $object
)
{
}

Description

Class constructor to initialize database connection and entity object.

Parameters

$database

Database connection or null

$object

Entity object to be handled

2. nullOrEmpty

Declaration

public static function nullOrEmpty(
    string $string
) : bool
{
}

Description

Check if a given string is null or empty.

Parameters

$string

The string to check

Return

bool

True if the string is null or empty, false otherwise

3. notNullAndNotEmpty

Declaration

public static function notNullAndNotEmpty(
    string $string
) : bool
{
}

Description

Check if a given string is not null and not empty.

Parameters

$string

The string to check

Return

bool

True if the string is not null and not empty, false otherwise

4. applySubqueryResult

Declaration

public static function applySubqueryResult(
    array $data,
    array $row,
    array $subqueryMap
) : array
{
}

Description

Apply results from a subquery to master data.

Parameters

$data

Master data to which subquery results will be applied

$row

Reference data containing subquery results

$subqueryMap

Mapping information for subqueries

Return

array

Updated master data with applied subquery results

5. includeNull

Declaration

public function includeNull(
    bool $skip
) : self
{
}

Description

Set a flag to include or skip null columns in the operation.

Parameters

$skip

Flag indicating whether to skip null columns

Return

self

Returns the current instance for method chaining

6. parseKeyValue

Declaration

private function parseKeyValue(
    PicoAnnotationParser $reflexClass,
    string $queryString,
    string $parameter
) : array
{
}

Description

Parse a key-value string using a specified parser.

Parameters

$reflexClass

The class used for parsing

$queryString

The key-value string to parse

$parameter

The name of the parameter being parsed

Return

array

Parsed key-value pairs

Throws

InvalidAnnotationException

If the annotations are invalid or cannot be parsed.

7. addColumnName

Declaration

private function addColumnName(
    array $columns,
    PicoAnnotationParser $reflexProp,
    ReflectionProperty $prop,
    array $parameters
) : array
{
}

Description

Add column name to the columns array based on provided parameters.

Parameters

$columns

The current columns array

$reflexProp

The property parser

$prop

The property reflection instance

$parameters

Parameters containing column name annotations

Return

array

Updated columns array with new column names

8. addColumnType

Declaration

private function addColumnType(
    array $columns,
    PicoAnnotationParser $reflexProp,
    ReflectionProperty $prop,
    array $parameters
) : array
{
}

Description

Add column type information to the columns array.

Parameters

$columns

The current columns array

$reflexProp

The property parser

$prop

The property reflection instance

$parameters

Parameters containing column type annotations

Return

array

Updated columns array with new column types

9. addJoinColumnName

Declaration

private function addJoinColumnName(
    array $joinColumns,
    PicoAnnotationParser $reflexProp,
    ReflectionProperty $prop,
    array $parameters
) : array
{
}

Description

Add a join column name to the join columns array.

Parameters

$joinColumns

The current join columns array

$reflexProp

The property parser for the current property

$prop

The reflection property instance

$parameters

Parameters containing join column annotations

Return

array

Updated join columns array with the new column name

10. addJoinColumnType

Declaration

private function addJoinColumnType(
    array $joinColumns,
    ReflectionProperty $prop,
    array $parameters
) : array
{
}

Description

Add a join column type to the join columns array.

Parameters

$joinColumns

The current join columns array

$prop

The reflection property instance

$parameters

Parameters containing join column type annotations

Return

array

Updated join columns array with the new column type

11. addPrimaryKey

Declaration

private function addPrimaryKey(
    array $primaryKeys,
    array $columns,
    ReflectionProperty $prop,
    array $parameters
) : array
{
}

Description

Add primary key information to the primary keys array.

Parameters

$primaryKeys

The current primary keys array

$columns

The columns array

$prop

The reflection property instance

$parameters

Parameters containing primary key annotations

Return

array

Updated primary keys array with the new primary key

12. addAutogenerated

Declaration

private function addAutogenerated(
    array $autoIncrementKeys,
    array $columns,
    PicoAnnotationParser $reflexClass,
    ReflectionProperty $prop,
    array $parameters
) : array
{
}

Description

Add autogenerated key information to the auto-increment keys array.

Parameters

$autoIncrementKeys

The current auto-increment keys array

$columns

The columns array

$reflexClass

The property parser

$prop

The reflection property instance

$parameters

Parameters containing auto-generated value annotations

Return

array

Updated auto-increment keys array with new autogenerated key

13. addDefaultValue

Declaration

private function addDefaultValue(
    array $defaultValue,
    array $columns,
    PicoAnnotationParser $reflexClass,
    ReflectionProperty $prop,
    array $parameters
) : array
{
}

Description

Add default value information to the default values array.

Parameters

$defaultValue

The current default values array

$columns

The columns array

$reflexClass

The property parser

$prop

The reflection property instance

$parameters

Parameters containing default value annotations

Return

array

Updated default values array with new default value

14. addNotNull

Declaration

private function addNotNull(
    array $notNullColumns,
    array $columns,
    ReflectionProperty $prop,
    array $parameters
) : array
{
}

Description

Add not-null column information to the not-null columns array.

Parameters

$notNullColumns

The current not-null columns array

$columns

The columns array

$prop

The reflection property instance

$parameters

Parameters containing not-null annotations

Return

array

Updated not-null columns array with new not-null column

15. getTableInfo

Declaration

public function getTableInfo() : PicoTableInfo
{
}

Description

Get table information by parsing class and property annotations.

Return

PicoTableInfo

Table information based on parsed annotations

Throws

EntityException

If the entity is invalid

16. matchRow

Declaration

public function matchRow(
    PDOStatement $stmt,
    string|null $databaseType = null
) : bool
{
}

Description

Check if the given PDO statement matches any rows.

Parameters

$stmt

PDO statement to check.

$databaseType

Optional database type, for specific behavior (e.g., SQLite).

Return

bool

True if rows match, false otherwise.

17. save

Declaration

public function save(
    bool $includeNull = false
) : PDOStatement|EntityException
{
}

Description

Save the current object to the database.

Parameters

$includeNull

Whether to include NULL values in the save operation.

Return

PDOStatement|EntityException

Returns the executed statement on success or throws an exception on failure.

18. saveQuery

Declaration

public function saveQuery(
    bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}

Description

Construct a query for saving the current object data.

Parameters

$includeNull

Whether to include NULL values in the query.

Return

PicoDatabaseQueryBuilder

Returns the constructed query builder for the save operation.

Throws

EntityException

If an error occurs while constructing the query.

19. getValues

Declaration

private function getValues(
    PicoTableInfo $info,
    PicoDatabaseQueryBuilder $queryBuilder
) : array
{
}

Description

Retrieve the values of the object for database operations.

Parameters

$info

Table information containing column definitions.

$queryBuilder

Query builder for escaping values.

Return

array

Associative array of column names and their corresponding values.

20. getNullCols

Declaration

private function getNullCols(
    PicoTableInfo $info
) : array
{
}

Description

Get a list of columns that should be set to NULL.

Parameters

$info

Table information containing column definitions.

Return

array

List of column names that should be set to NULL.

21. getNonInsertableCols

Declaration

private function getNonInsertableCols(
    PicoTableInfo $info
) : array
{
}

Description

Retrieve a list of columns that are not insertable.

Parameters

$info

Table information containing column definitions.

Return

array

List of non-insertable column names.

22. getNonUpdatableCols

Declaration

private function getNonUpdatableCols(
    PicoTableInfo $info
) : array
{
}

Description

Retrieve a list of columns that are not updatable.

Parameters

$info

Table information containing column definitions.

Return

array

List of non-updatable column names.

23. getSet

Declaration

private function getSet(
    PicoTableInfo $info,
    PicoDatabaseQueryBuilder $queryBuilder
) : string
{
}

Description

Construct the SET statement for an SQL update operation.

Parameters

$info

Table information containing column definitions.

$queryBuilder

Query builder for escaping values.

Return

string

The constructed SET clause for the update statement.

Throws

NoUpdatableColumnException

If no updatable columns are found.

24. getWhere

Declaration

private function getWhere(
    PicoTableInfo $info,
    PicoDatabaseQueryBuilder $queryBuilder
) : string
{
}

Description

Construct the WHERE statement for SQL operations.

Parameters

$info

Table information containing primary key definitions.

$queryBuilder

Query builder for escaping values.

Return

string

The constructed WHERE clause.

Throws

NoPrimaryKeyDefinedException

If no primary keys are defined.

25. getPrimaryKeys

Declaration

public function getPrimaryKeys(
    PicoTableInfo|null $info = null
) : array
{
}

Description

Retrieve the primary keys from the table information.

Parameters

$info

Optional table information; if null, it retrieves the current table info.

Return

array

List of primary key column names.

Throws

EntityException

If an error occurs while retrieving primary keys.

26. getColumns

Declaration

public function getColumns(
    PicoTableInfo|null $info = null
) : array
{
}

Description

Retrieve all column names from the table information.

Parameters

$info

Optional table information; if null, it retrieves the current table info.

Return

array

List of column names.

Throws

EntityException

If an error occurs while retrieving columns.

27. getJoinSources

Declaration

public function getJoinSources(
    PicoTableInfo|null $info = null
) : array
{
}

Description

Retrieve all join column names from the table information.

Parameters

$info

Optional table information; if null, it retrieves the current table info.

Return

array

List of join column names.

Throws

EntityException

If an error occurs while retrieving join columns.

28. isPrimaryKeys

Declaration

public function isPrimaryKeys(
    string $columnName,
    array $primaryKeys
) : bool
{
}

Description

Check if the specified column name is a primary key.

Parameters

$columnName

The name of the column to check.

$primaryKeys

An array of primary key column names.

Return

bool

True if the column is a primary key, false otherwise.

29. getPrimaryKeyAutoIncrement

Declaration

public function getPrimaryKeyAutoIncrement(
    PicoTableInfo $info
) : array
{
}

Description

Retrieve primary keys that have auto-increment values.

Parameters

$info

Information about the table, including key definitions.

Return

array

An associative array of auto-increment primary keys and their values.

30. addGeneratedValue

Declaration

private function addGeneratedValue(
    PicoTableInfo $info,
    bool $firstCall
) : self
{
}

Description

Add generated values for auto-increment or UUID fields.

Parameters

$info

Table information.

$firstCall

Indicates whether this is the first call to the method.

Return

self

Fluent interface; returns the current instance.

31. setGeneratedValue

Declaration

private function setGeneratedValue(
    string $prop,
    string $strategy,
    bool $firstCall
) : self
{
}

Description

Set a generated value for a specified property based on its generation strategy.

Parameters

$prop

The property name to set the generated value for.

$strategy

The generation strategy to use (e.g., UUID, IDENTITY).

$firstCall

Indicates whether this is the first call to the method.

Return

self

Fluent interface; returns the current instance.

32. insert

Declaration

public function insert(
    bool $includeNull = false
) : PDOStatement|EntityException
{
}

Description

Insert the current object's data into the database.

Parameters

$includeNull

Whether to include NULL values in the insert operation.

Return

PDOStatement|EntityException

Returns the executed statement on success or throws an exception on failure.

33. insertQuery

Declaration

public function insertQuery(
    bool $includeNull = false
) : PicoDatabaseQueryBuilder|EntityException
{
}

Description

Construct the query for inserting the current object's data.

Parameters

$includeNull

Whether to include NULL values in the insert query.

Return

PicoDatabaseQueryBuilder|EntityException

Returns the constructed query builder or throws an exception on failure.

34. _insert

Declaration

private function _insert(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null
) : PDOStatement
{
}

Description

Execute the insert operation using the given table information and query builder.

Parameters

$info

Table information.

$queryBuilder

Query builder for the insert operation.

Return

PDOStatement

The executed statement.

35. _insertQuery

Declaration

private function _insertQuery(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null
) : PicoDatabaseQueryBuilder
{
}

Description

Construct the SQL insert query using the provided table information and query builder.

Parameters

$info

Table information.

$queryBuilder

Query builder for the insert operation.

Return

PicoDatabaseQueryBuilder

The constructed query builder.

Throws

EntityException

If an error occurs while constructing the query.

36. fixInsertableValues

Declaration

private function fixInsertableValues(
    array $values,
    PicoTableInfo|null $info = null
) : array
{
}

Description

Filter the values to only include those that are insertable based on table info.

Parameters

$values

Values to be filtered.

$info

Table information.

Return

array

The filtered array of insertable values.

Throws

NoInsertableColumnException

If no values are found that can be inserted.

37. isRequireGenerateValue

Declaration

private function isRequireGenerateValue(
    string $strategy,
    string $propertyName
) : bool
{
}

Description

Check if a generated value is required based on the strategy and property name.

Parameters

$strategy

The generation strategy for the property.

$propertyName

The name of the property to check.

Return

bool

True if a generated value is required, false otherwise.

38. createStatementFields

Declaration

public function createStatementFields(
    array $values
) : string
{
}

Description

Create a comma-separated string of field names for an SQL insert statement.

Parameters

$values

An associative array of values where keys are field names.

Return

string

A string representation of the field names.

39. createStatementValues

Declaration

public function createStatementValues(
    array $values
) : string
{
}

Description

Create a comma-separated string of values for an SQL insert statement.

Parameters

$values

An associative array of values.

Return

string

A string representation of the values.

40. getColumnNames

Declaration

private function getColumnNames(
    string $propertyNames,
    array $columns
) : string
{
}

Description

Convert a property name to its corresponding database column name.

Parameters

$propertyNames

A string containing property names.

$columns

An array of column definitions.

Return

string

The resulting string with column names.

Throws

NoColumnMatchException

If no column matches the provided property names.

41. getColumnMap

Declaration

private function getColumnMap(
    PicoTableInfo $info
) : array
{
}

Description

Get a mapping of columns from the provided table information.

Parameters

$info

Table information.

Return

array

An associative array mapping property names to column names.

42. fixComparison

Declaration

private function fixComparison(
    string $column
) : string
{
}

Description

Adjust the comparison string for SQL queries.

Parameters

$column

The column comparison string.

Return

string

The adjusted comparison string.

43. createWhereFromArgs

Declaration

private function createWhereFromArgs(
    PicoTableInfo $info,
    string $propertyName,
    array $propertyValues
) : string
{
}

Description

Create a SQL WHERE clause based on provided arguments.

Parameters

$info

Table information.

$propertyName

The name of the property to include in the WHERE clause.

$propertyValues

The values to compare against.

Return

string

The constructed WHERE clause.

44. getTableOf

Declaration

private function getTableOf(
    string|null $entityName,
    PicoTableInfo $info
) : string|null
{
}

Description

Get table name of the entity

Parameters

$entityName

Entity name

$info

Table information

Return

string|null

The corresponding table name or null if not found

Throws

Exception

If unable to retrieve the class name or parse annotations

45. getPrimaryKeyOf

Declaration

private function getPrimaryKeyOf(
    string $entityName,
    PicoTableInfo $info
) : string[]
{
}

Description

Get entity primary key of the entity

Parameters

$entityName

Entity name

$info

Table information

Return

string[]

Array of primary key column names

Throws

ClassNotFoundException

If unable to retrieve the class name or parse annotations

46. getColumnMapOf

Declaration

private function getColumnMapOf(
    string $entityName,
    PicoTableInfo $info
) : array
{
}

Description

Get column maps of the entity

Parameters

$entityName

Entity name

$info

Table information

Return

array

Associative array mapping property names to column names

Throws

ClassNotFoundException

If unable to retrieve the class name or parse annotations

47. getJoinSource

Declaration

private function getJoinSource(
    string|null $parentName,
    string $masterTable,
    string|null $entityTable,
    string $field,
    bool $master = false
) : string
{
}

Description

Get join source

Parameters

$parentName

Parent name

$masterTable

Master table

$entityTable

Entity table

$field

Field name

$master

Indicates if the master table is being used

Return

string

Fully qualified column name for the join

48. createWhereFromSpecification

Declaration

protected function createWhereFromSpecification(
    PicoDatabaseQueryBuilder $sqlQuery,
    PicoSpecification $specification,
    PicoTableInfo $info
) : string
{
}

Description

Create WHERE clause from specification

Parameters

$sqlQuery

Query builder instance

$specification

Specification containing filter criteria

$info

Table information

Return

string

The constructed WHERE clause

49. joinStringArray

Declaration

private function joinStringArray(
    string[] $arr,
    int $max = 0,
    string $normalSplit = ' ',
    string $maxSplit = ' '
) : string
{
}

Description

Join array of strings with a maximum length for each line

Parameters

$arr

Array of strings to join

$max

Maximum length of each line

$normalSplit

Normal splitter for joining

$maxSplit

Splitter for overflow lines

Return

string

Joined string with line breaks as necessary

50. splitChunk

Declaration

private function splitChunk(
    string[] $arr,
    int $max,
    string $normalSplit
) : array
{
}

Description

Split array into chunks based on maximum length

Parameters

$arr

Array of strings to split

$max

Maximum length for each chunk

$normalSplit

Normal splitter for joining

Return

array

Array of string chunks

51. addWhere

Declaration

private function addWhere(
    array $arr,
    array $masterColumnMaps,
    PicoDatabaseQueryBuilder $sqlQuery,
    PicoSpecification $spec,
    PicoTableInfo $info
) : array
{
}

Description

Add WHERE statement to the query

Parameters

$arr

Array of existing WHERE clauses

$masterColumnMaps

Master column mappings

$sqlQuery

Query builder instance

$spec

Specification to process

$info

Table information

Return

array

Updated array of WHERE clauses

52. constructSpecificationQuery

Declaration

private function constructSpecificationQuery(
    PicoDatabaseQueryBuilder $sqlQuery,
    PicoSpecification $spec,
    string $columnFinal
) : string
{
}

Description

Constructs an SQL query fragment based on the given specification.

Parameters

$sqlQuery

Query builder instance.

$spec

Specification containing comparison logic and values.

$columnFinal

The database column to be compared.

Return

string

The constructed SQL query fragment.

53. contructComparisonValue

Declaration

private function contructComparisonValue(
    PicoPredicate $predicate,
    PicoDatabaseQueryBuilder $sqlQuery
) : string
{
}

Description

Construct comparison value for predicates

Parameters

$predicate

Predicate with comparison values

$sqlQuery

Query builder instance

Return

string

Formatted comparison value for SQL query

54. formatColumn

Declaration

private function formatColumn(
    string $column,
    string|null $format
) : string
{
}

Description

Format column name with optional formatting

Parameters

$column

Column name to format

$format

Formatting string

Return

string

Formatted column name

55. createOrderBy

Declaration

private function createOrderBy(
    PicoTableInfo $info,
    PicoSortable|string $order
) : string|null
{
}

Description

Create ORDER BY clause

Parameters

$info

Table information

$order

Sorting criteria

Return

string|null

The constructed ORDER BY clause or null

56. createOrderByQuery

Declaration

public function createOrderByQuery(
    PicoSortable $order,
    PicoTableInfo|null $info = null
) : string|null
{
}

Description

Create sorting SQL query

Parameters

$order

Sorting criteria

$info

Table information

Return

string|null

The constructed ORDER BY clause or null

57. createWithoutMapping

Declaration

private function createWithoutMapping(
    PicoSortable $order,
    PicoTableInfo|null $info
) : string|null
{
}

Description

Create sorting without mapping

Parameters

$order

Sorting criteria

$info

Table information

Return

string|null

The constructed ORDER BY clause or null

58. createWithMapping

Declaration

private function createWithMapping(
    PicoSortable $order,
    PicoTableInfo $info
) : string
{
}

Description

Create sorting with mapping

Parameters

$order

Sorting criteria

$info

Table information

Return

string

The constructed ORDER BY clause

59. isValidPrimaryKeyValues

Declaration

private function isValidPrimaryKeyValues(
    string[] $primaryKeys,
    array $propertyValues
) : bool
{
}

Description

Check if primary keys have valid values

Parameters

$primaryKeys

Array of primary key names

$propertyValues

Property values to check

Return

bool

True if primary keys are valid, false otherwise

60. toArray

Declaration

private function toArray(
    mixed $propertyValues
) : array
{
}

Description

Convert a scalar value to an array

Parameters

$propertyValues

Property values to convert

Return

array

Converted array of property values

61. getAllColumns

Declaration

private function getAllColumns(
    PicoTableInfo $info
) : string
{
}

Description

Get all columns of the entity

Parameters

$info

Table information

Return

string

Comma-separated string of all column names

62. find

Declaration

public function find(
    mixed $propertyValues
) : object
{
}

Description

Finds a single record by its primary key value(s).

This method retrieves a single record from the database that matches the specified primary key value(s). It returns the found record as an object. If no record is found or if the filter is invalid, appropriate exceptions will be thrown.

Parameters

$propertyValues

The primary key value(s) used to find the record.

Return

object

The found record, or null if not found.

Throws

EntityException

If there is an issue with the entity.

InvalidFilterException

If the provided filter criteria are invalid.

EmptyResultException

If no record is found or no primary key is set.

63. createWhereByPrimaryKeys

Declaration

private function createWhereByPrimaryKeys(
    PicoDatabaseQueryBuilder $queryBuilder,
    array $primaryKeys,
    mixed $propertyValues
) : string
{
}

Description

Creates the WHERE clause for the query based on the primary keys and their values.

This method constructs a WHERE clause for the SQL query using the provided primary key names and values. It checks for null values and properly escapes the values for security.

Parameters

$queryBuilder

The query builder instance used to create the SQL query.

$primaryKeys

The primary keys of the table.

$propertyValues

The values for the primary keys.

Return

string

The constructed WHERE clause.

Throws

InvalidFilterException

If the constructed filter is invalid.

64. setSpecification

Declaration

private function setSpecification(
    PicoDatabaseQueryBuilder $sqlQuery,
    PicoSpecification|array $specification,
    PicoTableInfo $info
) : PicoDatabaseQueryBuilder
{
}

Description

Add specification to query builder

Parameters

$sqlQuery

Query builder instance

$specification

Specification or specifications array

$info

Table information

Return

PicoDatabaseQueryBuilder

Modified query builder with specification applied

65. setPageable

Declaration

private function setPageable(
    PicoDatabaseQueryBuilder $sqlQuery,
    PicoPageable $pageable
) : PicoDatabaseQueryBuilder
{
}

Description

Add pageable to query builder

Parameters

$sqlQuery

Query builder instance

$pageable

Pageable object

Return

PicoDatabaseQueryBuilder

Modified query builder with pageable applied

66. setSortable

Declaration

private function setSortable(
    PicoDatabaseQueryBuilder $sqlQuery,
    PicoPageable|null $pageable,
    PicoSortable|string|null $sortable,
    PicoTableInfo $info
) : PicoDatabaseQueryBuilder
{
}

Description

Add sortable to query builder

Parameters

$sqlQuery

Query builder instance

$pageable

Pageable object (optional)

$sortable

Sortable object or field name (optional)

$info

Table information

Return

PicoDatabaseQueryBuilder

Modified query builder with sortable applied

67. setOrdeBy

Declaration

private function setOrdeBy(
    PicoDatabaseQueryBuilder $sqlQuery,
    string $sortOrder
) : PicoDatabaseQueryBuilder
{
}

Description

Set ORDER BY clause in the query

Parameters

$sqlQuery

Query builder instance

$sortOrder

Sort order string

Return

PicoDatabaseQueryBuilder

Modified query builder with ORDER BY clause

68. addJoinQuery

Declaration

protected function addJoinQuery(
    PicoDatabaseQueryBuilder $sqlQuery,
    PicoTableInfo $info
) : PicoDatabaseQueryBuilder
{
}

Description

Add JOIN query to the query builder

Parameters

$sqlQuery

Query builder instance

$info

Table information

Return

PicoDatabaseQueryBuilder

Modified query builder with JOIN clauses

69. isRequireJoin

Declaration

protected function isRequireJoin(
    PicoSpecification $specification,
    PicoPageable|null $pageable,
    PicoSortable|string|null $sortable,
    PicoTableInfo $info
) : bool
{
}

Description

Check if JOIN query is required based on specification, pageable, and sortable

Parameters

$specification

Specification object

$pageable

Pageable object (optional)

$sortable

Sortable object or field name (optional)

$info

Table information

Return

bool

True if JOIN is required, otherwise false

70. isRequireJoinFromPageableAndSortable

Declaration

private function isRequireJoinFromPageableAndSortable(
    PicoPageable|null $pageable,
    PicoSortable|string|null $sortable,
    PicoTableInfo $info
) : bool
{
}

Description

Determine if JOIN is required based on pageable and sortable

Parameters

$pageable

Pageable object (optional)

$sortable

Sortable object or field name (optional)

$info

Table information

Return

bool

True if JOIN is required, otherwise false

71. isRequireJoinFromSpecification

Declaration

private function isRequireJoinFromSpecification(
    PicoSpecification $specification
) : bool
{
}

Description

Determine if JOIN is required based on specification

Parameters

$specification

Specification object

Return

bool

True if JOIN is required, otherwise false

72. createPDOStatement

Declaration

public function createPDOStatement(
    PicoSpecification $specification,
    PicoPageable $pageable,
    PicoSortable $sortable,
    array|null $subqueryMap = null,
    string|null $selected = null
) : PDOStatement
{
}

Description

Create a PDO statement based on specification, pageable, sortable, and selected fields

Parameters

$specification

Specification object

$pageable

Pageable object

$sortable

Sortable object

$subqueryMap

Subquery map (optional)

$selected

Selected fields (optional)

Return

PDOStatement

Prepared PDO statement

Throws

PDOException

If there is an error in PDO operations

73. findAllQuery

Declaration

public function findAllQuery(
    PicoSpecification|null $specification,
    PicoPageable|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    PicoTableInfo|null $info = null
) : PicoDatabaseQueryBuilder
{
}

Description

Get query to find all records from the database without any filter

Parameters

$specification

Specification object (optional)

$pageable

Pageable object (optional)

$sortable

Sortable object or field name (optional)

$info

Table information (optional)

Return

PicoDatabaseQueryBuilder

Query builder for finding all records

74. findSpecificQuery

Declaration

public function findSpecificQuery(
    string $selected,
    PicoSpecification|null $specification,
    PicoPageable|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    PicoTableInfo|null $info = null
) : PicoDatabaseQueryBuilder
{
}

Description

Get findSpecific query builder

Parameters

$selected

The columns to select

$specification

Specification to filter results

$pageable

Pageable information for pagination

$sortable

Sort order for the results

$info

Table information (optional, defaults to current table info)

Return

PicoDatabaseQueryBuilder

The configured query builder

75. findOne

Declaration

public function findOne(
    PicoSpecification|null $specification,
    PicoSortable|string|null $sortable = null,
    array|null $subqueryMap = null
) : array|null
{
}

Description

Retrieve a single record from the database without filters

Parameters

$specification

Specification to filter results

$sortable

Sort order for the results

$subqueryMap

Optional subquery mappings

Return

array|null

The retrieved record or null if not found

Throws

EntityException|EmptyResultException

If no results are found

76. findAll

Declaration

public function findAll(
    PicoSpecification|null $specification,
    PicoPageable|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    array|null $subqueryMap = null
) : array|null
{
}

Description

Retrieve all records from the database without filters

Parameters

$specification

Specification to filter results

$pageable

Pageable information for pagination

$sortable

Sort order for the results

$subqueryMap

Optional subquery mappings

Return

array|null

The list of records or null if not found

Throws

EntityException|EmptyResultException

If no results are found

77. findOneWithPrimaryKeyValue

Declaration

public function findOneWithPrimaryKeyValue(
    mixed $primaryKeyVal,
    array $subqueryMap
) : array|null
{
}

Description

Find a record by its primary key value

Parameters

$primaryKeyVal

The value of the primary key

$subqueryMap

Optional subquery mappings

Return

array|null

The retrieved record or null if not found

Throws

EmptyResultException

If no record is found

78. findSpecificWithSubquery

Declaration

public function findSpecificWithSubquery(
    string $selected,
    PicoSpecification $specification,
    PicoPageable|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    array|null $subqueryMap = null
) : array|null
{
}

Description

Retrieve records from the database with optional subqueries

Parameters

$selected

The columns to select

$specification

Specification to filter results

$pageable

Pageable information for pagination

$sortable

Sort order for the results

$subqueryMap

Optional subquery mappings

Return

array|null

The list of records or null if not found

Throws

EntityException|EmptyResultException

If no results are found

79. subquery

Declaration

public function subquery(
    PicoTableInfo $info,
    array $subqueryMap
) : string
{
}

Description

Create a subquery based on the provided mapping

Parameters

$info

Table information

$subqueryMap

Mapping for subqueries

Return

string

The generated subquery string

80. joinString

Declaration

public function joinString(
    string $string1,
    string $string2,
    string $separator
) : string
{
}

Description

Concatenate two strings with a separator

Parameters

$string1

The first string

$string2

The second string

$separator

The separator to use

Return

string

The concatenated string

81. findSpecific

Declaration

public function findSpecific(
    string $selected,
    PicoSpecification $specification,
    PicoPageable|null $pageable = null,
    PicoSortable|string|null $sortable = null
) : array|null
{
}

Description

Retrieve specific records from the database

Parameters

$selected

The columns to select

$specification

Specification to filter results

$pageable

Pageable information for pagination

$sortable

Sort order for the results

Return

array|null

The list of records or null if not found

Throws

EntityException|EmptyResultException

If no results are found

82. findByQuery

Declaration

public function findByQuery(
    string $propertyName,
    mixed $propertyValue,
    PicoPageable|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    PicoTableInfo $info = null,
    array|null $subqueryMap = null
) : PicoDatabaseQueryBuilder
{
}

Description

Build a query for matched records based on specified criteria

Parameters

$propertyName

The property name to filter by

$propertyValue

The value of the property to filter by

$pageable

Pageable information for pagination

$sortable

Sort order for the results

$info

Table information

$subqueryMap

Optional subquery mappings

Return

PicoDatabaseQueryBuilder

The configured query builder

Throws

PDOException|NoDatabaseConnectionException|EntityException

If an error occurs

83. findBy

Declaration

public function findBy(
    string $propertyName,
    mixed $propertyValue,
    PicoPageable|null $pageable = null,
    PicoSortable|string|null $sortable = null,
    array|null $subqueryMap = null
) : array|null
{
}

Description

Retrieve matched records from the database

Parameters

$propertyName

The property name to filter by

$propertyValue

The value of the property to filter by

$pageable

Pageable information for pagination

$sortable

Sort order for the results

$subqueryMap

Optional subquery mappings

Return

array|null

The list of matched records or null if not found

Throws

PDOException|NoDatabaseConnectionException|EntityException

If an error occurs

84. existsBy

Declaration

public function existsBy(
    string $propertyName,
    mixed $propertyValue
) : bool
{
}

Description

Check if a record exists based on property criteria

Parameters

$propertyName

The property name to check

$propertyValue

The value of the property to check

Return

bool

True if the record exists, false otherwise

85. countAll

Declaration

public function countAll(
    PicoSpecification|null $specification = null,
    PicoPageable|null $pageable = null,
    PicoSortable|null $sortable = null
) : int
{
}

Description

Count the total number of records without filters

Parameters

$specification

Specification to filter results

$pageable

Pageable information for pagination

$sortable

Sort order for the results

Return

int

The count of records

Throws

EntityException|EmptyResultException

If an error occurs

86. countBy

Declaration

public function countBy(
    string $propertyName,
    mixed $propertyValue
) : int
{
}

Description

Count records based on specified criteria.

Parameters

$propertyName

The property name to filter by.

$propertyValue

The value of the property to filter by.

Return

int

The count of matched records.

Throws

EntityException|InvalidFilterException|PDOException|EmptyResultException

If an error occurs.

87. deleteBy

Declaration

public function deleteBy(
    string $propertyName,
    mixed $propertyValue
) : int
{
}

Description

Delete records based on specified criteria without reading them first

Parameters

$propertyName

The property name to filter by

$propertyValue

The value of the property to filter by

Return

int

The number of deleted records

Throws

EntityException|InvalidFilterException|PDOException|EmptyResultException

If an error occurs

88. findOneBy

Declaration

public function findOneBy(
    string $propertyName,
    mixed $propertyValue,
    PicoSortable|string|null $sortable = null
) : array|null
{
}

Description

Retrieves a single matched record from the database based on the specified property name and value.

This method constructs a SQL query to find a single record that matches the provided property name and value. It can also sort the results based on the optional sortable parameter. If no record is found, it returns null.

Parameters

$propertyName

The name of the property to filter the records by.

$propertyValue

The value of the property to match against.

$sortable

Optional. Defines sorting for the result set.

Return

array|null

Returns the matching record as an associative array, or null if no record is found.

Throws

EntityException

If there is an issue with the entity operations.

InvalidFilterException

If the constructed filter is invalid.

EmptyResultException

If the query results in an empty set.

89. getRealClassName

Declaration

private function getRealClassName(
    string $classNameJoin,
    PicoTableInfo $info
) : string
{
}

Description

Retrieves the fully qualified class name based on the given class name and table information.

If the class name does not include a namespace, it constructs the full class name using the package information from the provided PicoTableInfo. If the package is not defined, it attempts to resolve the class name from the current namespace or imported classes.

Parameters

$classNameJoin

The class name to join.

$info

Table information containing package details.

Return

string

The fully qualified class name, which may include the package or namespace.

90. getRealClassNameWithoutPackage

Declaration

private function getRealClassNameWithoutPackage(
    string $classNameJoin
) : string
{
}

Description

Resolves the fully qualified class name when no package is defined.

This method checks if the class name is present in the imported class list or assumes it belongs to the current namespace if not found. It processes the class list only once to improve efficiency.

Parameters

$classNameJoin

The class name to join.

Return

string

The fully qualified class name from the imported list or the same namespace.

91. getReferenceColumnName

Declaration

private function getReferenceColumnName(
    array $join
) : string
{
}

Description

Retrieves the reference column name from the provided join information.

This method checks if the join array contains a specific key for the reference column name. If the key exists, it returns that value; otherwise, it returns the standard column name.

Parameters

$join

The join column definition, which may include keys for reference and standard column names.

Return

string

The reference column name, either from the specific key or the standard name.

92. getJoinKeyName

Declaration

private function getJoinKeyName(
    string $classNameJoin,
    string $referenceColumName,
    PicoTableInfo $info
) : string|null
{
}

Description

Retrieves the property name corresponding to the given reference column name from a joined class.

This method checks the columns of the specified class, and returns the property name that matches the reference column name. If no match is found, it returns the reference column name itself.

Parameters

$classNameJoin

The name of the class to join with.

$referenceColumName

The name of the reference column to look up.

$info

The table information containing metadata about the columns.

Return

string|null

The corresponding property name if found, otherwise the reference column name.

93. prepareJoinCache

Declaration

private function prepareJoinCache(
    string $classNameJoin
) : self
{
}

Description

Prepares the join cache for a specified class name.

This method checks if the join cache for the given class name exists. If it does not exist, it initializes an empty array for caching join data. It ensures that the join cache is ready for storing results from subsequent queries.

Parameters

$classNameJoin

The class name for which to prepare the join cache.

Return

self

Returns the current instance for method chaining.

94. getJoinData

Declaration

private function getJoinData(
    string $classNameJoin,
    string $referenceColumnName,
    mixed $joinKeyValue,
    PicoTableInfo $info
) : MagicObject|null
{
}

Description

Retrieves joined data based on the specified class name and key value.

This method checks the join cache for previously retrieved data. If the data is not found in the cache, it creates a new instance of the specified class, sets the appropriate database connection, and retrieves the data using the specified join key.

Parameters

$classNameJoin

The name of the class to join with.

$referenceColumnName

The name of the column used as the join key.

$joinKeyValue

The value of the join key to search for.

$info

Table information

Return

MagicObject|null

Returns the retrieved MagicObject if found, or null if not found.

95. join

Declaration

public function join(
    mixed $data,
    array $row,
    PicoTableInfo $info
) : mixed
{
}

Description

Joins data based on the specified join columns from the provided row.

This method retrieves related data by following the join definitions specified in the PicoTableInfo object. It populates the given data object with the joined entities based on the annotations defined in the join columns.

Parameters

$data

The original object or array to be populated with joined data.

$row

The row of data containing column values.

$info

The table information that includes join column metadata.

Return

mixed

The updated object or array with joined data.

96. addProperty

Declaration

private function addProperty(
    array|object $data,
    string $propName,
    mixed $value
) : array|object
{
}

Description

Adds a property to the original data array or object.

This method sets a property with the specified name to the given value. It handles both arrays and objects, ensuring that the property is added correctly based on the type.

Parameters

$data

The original data (array or object).

$propName

The name of the property to add.

$value

The value to assign to the property.

Return

array|object

The updated data array or object with the new property.

97. isValidFilter

Declaration

private function isValidFilter(
    string $filter
) : bool
{
}

Description

Validates whether the given filter is acceptable.

This method checks if the provided filter is not null, not empty, and not a whitespace string.

Parameters

$filter

The filter string to validate.

Return

bool

True if the filter is valid; otherwise, false.

98. notNullAndNotEmptyAndNotSpace

Declaration

private function notNullAndNotEmptyAndNotSpace(
    string $value
) : bool
{
}

Description

Checks if the provided value is not null, not empty, and not just whitespace.

This method trims the input value and performs checks to determine if it is a valid, non-empty string.

Parameters

$value

The value to check.

Return

bool

True if the value is valid; otherwise, false.

99. fixDataType

Declaration

public function fixDataType(
    array $data,
    PicoTableInfo $info
) : array
{
}

Description

Fixes the data types of the input data based on the table information.

This method maps the input data to the appropriate types as defined in the provided PicoTableInfo. It ensures that the data types are correct according to the column definitions.

Parameters

$data

The input data to be fixed.

$info

The table information containing type definitions.

Return

array

The data with fixed types.

100. fixData

Declaration

public function fixData(
    mixed $value,
    string $type
) : mixed
{
}

Description

Fixes the value to the specified data type.

This method converts the input value to the appropriate type based on the provided data type. It handles various types including boolean, integer, double, and DateTime.

Parameters

$value

The input value to be fixed.

$type

The expected data type of the value.

Return

mixed

The value converted to the specified type.

101. boolval

Declaration

private function boolval(
    mixed $value
) : bool
{
}

Description

Converts the input value to a boolean.

This method checks if the input value is equivalent to 1 or '1' to determine if it should return true; otherwise, it returns false.

Parameters

$value

The input value to convert.

Return

bool

True if the value is equivalent to 1; otherwise, false.

102. intval

Declaration

private function intval(
    mixed $value
) : mixed
{
}

Description

Converts the input value to an integer.

This method returns the integer value of the input. If the input is null, it returns null instead.

Parameters

$value

The input value to convert.

Return

mixed

The integer value or null if the input is null.

103. doubleval

Declaration

private function doubleval(
    mixed $value
) : mixed
{
}

Description

Converts the input value to a double.

This method returns the double value of the input. If the input is null, it returns null instead.

Parameters

$value

The input value to convert.

Return

mixed

The double value or null if the input is null.

104. fixInput

Declaration

private function fixInput(
    mixed $value,
    array $column
) : mixed
{
}

Description

Fixes the input value based on its type and applies timezone adjustments if necessary.

If the input value is an instance of DateTime, it adjusts the timezone and formats the date according to the specified column format. If the input value is not a DateTime, it simply adjusts the timezone without formatting the value. If a date format is specified in the column, it will format the DateTime accordingly.

Parameters

$value

The input value to fix, which can be a DateTime object, string, or other types.

$column

The column information containing potential date format and type.

Return

mixed

The formatted date string if the input is a DateTime, or the original value after timezone adjustment.

105. fixTimeZone

Declaration

private function fixTimeZone(
    mixed $value,
    array $column,
    string|DateTimeZone $timeZoneFrom,
    string|DateTimeZone $timeZoneTo
) : mixed
{
}

Description

Adjusts the input value from the source timezone to the target timezone if necessary.

This method checks if the column type is related to a timestamp and the database is SQLite. If so, it adjusts the input value (which can be a DateTime object, string, or Unix timestamp) from the source timezone to the target timezone. Otherwise, it returns the original value.

Parameters

$value

The value to be adjusted. Can be a DateTime, string, or Unix timestamp.

$column

The column information containing potential date format and type.

$timeZoneFrom

The source timezone (either a string or DateTimeZone object).

$timeZoneTo

The target timezone (either a string or DateTimeZone object).

Return

mixed

The adjusted value, either a formatted DateTime or the original value if no adjustment is necessary.

106. isDateTimeNull

Declaration

private function isDateTimeNull(
    string $value
) : bool
{
}

Description

Checks if the given datetime value represents a null or empty datetime.

This method checks specific string representations of null or default datetime values.

Parameters

$value

The value to check.

Return

bool

True if the value represents a null datetime; otherwise, false.

107. createTypeMap

Declaration

private function createTypeMap(
    PicoTableInfo $info
) : array
{
}

Description

Creates a mapping of column names to their corresponding property types.

This method generates an associative array where keys are column names and values are their associated property types based on the provided PicoTableInfo.

Parameters

$info

The table information containing column metadata.

Return

array

An associative array mapping column names to property types.

108. select

Declaration

public function select() : mixed
{
}

Description

Selects record from the database based on the defined criteria.

This method builds a query to retrieve records from the database using the current table information, filters, specifications, and pagination settings.

Return

mixed

The result set of the query.

Throws

EntityException

If an error occurs while selecting records.

109. selectAll

Declaration

public function selectAll() : mixed
{
}

Description

Selects all records from the database.

This method constructs and executes a query to retrieve all records from the specified table in the database.

Return

mixed

The result set containing all records.

Throws

EntityException

If an error occurs during the selection process.

110. selectQuery

Declaration

public function selectQuery() : PicoDatabaseQueryBuilder
{
}

Description

Builds a query to select data without executing it.

This method prepares a select query using the specified table information and filtering criteria but does not execute the query.

Return

PicoDatabaseQueryBuilder

The query builder with the select query prepared.

Throws

EntityException

If an error occurs while preparing the query.

111. _select

Declaration

private function _select(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null,
    string|null $where = null,
    mixed|null $specification = null,
    mixed|null $pageable = null,
    mixed|null $sortable = null
) : mixed
{
}

Description

Selects a record from the database based on primary keys.

This method constructs and executes a select query using the provided table information and filtering criteria. It returns the first matching record or null if none found.

Parameters

$info

The table information. If null, fetched internally.

$queryBuilder

The query builder. If null, created internally.

$where

The where clause for the query. If null, fetched internally.

$specification

Optional specifications for the query.

$pageable

Optional pagination settings for the query.

$sortable

Optional sorting settings for the query.

Return

mixed

The matching record or null if not found.

Throws

EntityException

If an error occurs during the selection process.

InvalidFilterException

If the provided filter is invalid.

EmptyResultException

If no result is found.

112. _selectAll

Declaration

private function _selectAll(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null,
    string|null $where = null,
    mixed|null $specification = null,
    mixed|null $pageable = null,
    mixed|null $sortable = null
) : array
{
}

Description

Selects all matching records from the database.

This method constructs and executes a select query to retrieve all records that match the specified filtering criteria. It returns an array of results.

Parameters

$info

The table information. If null, fetched internally.

$queryBuilder

The query builder. If null, created internally.

$where

The where clause for the query. If null, fetched internally.

$specification

Optional specifications for the query.

$pageable

Optional pagination settings for the query.

$sortable

Optional sorting settings for the query.

Return

array

An array of matching records.

Throws

EntityException

If an error occurs during the selection process.

InvalidFilterException

If the provided filter is invalid.

EmptyResultException

If no results are found.

113. _selectQuery

Declaration

private function _selectQuery(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null,
    string|null $where = null
) : PicoDatabaseQueryBuilder
{
}

Description

Prepares a query to select data without executing it.

This method constructs a select query using the specified table information and filtering criteria without executing it, allowing for further modifications if needed.

Parameters

$info

The table information. If null, fetched internally.

$queryBuilder

The query builder. If null, created internally.

$where

The where clause for the query. If null, fetched internally.

Return

PicoDatabaseQueryBuilder

The query builder with the select query prepared.

Throws

InvalidFilterException

If the provided filter is invalid.

EntityException

If an error occurs while preparing the query.

114. update

Declaration

public function update(
    bool $includeNull = false
) : PDOStatement
{
}

Description

Updates records in the database.

This method constructs and executes an update query to modify records in the specified table. It accepts an optional flag to include null values in the update.

Parameters

$includeNull

Optional. If true, null values are included in the update.

Return

PDOStatement

The executed update statement.

Throws

EntityException

If an error occurs during the update process.

115. updateQuery

Declaration

public function updateQuery(
    bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}

Description

Prepares an update query without executing it.

This method constructs an update query using the specified table information and returns the query builder for further modifications.

Parameters

$includeNull

Optional. If true, null values are included in the update.

Return

PicoDatabaseQueryBuilder

The query builder with the update query prepared.

Throws

EntityException

If an error occurs while preparing the query.

116. _update

Declaration

private function _update(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null,
    string|null $where = null
) : PDOStatement
{
}

Description

Updates a record in the database based on primary keys.

This method constructs and executes an update query using the provided table information and filtering criteria.

Parameters

$info

The table information. If null, fetched internally.

$queryBuilder

The query builder. If null, created internally.

$where

The where clause for the query. If null, fetched internally.

Return

PDOStatement

The executed update statement.

Throws

InvalidFilterException

If the provided filter is invalid.

117. _updateQuery

Declaration

private function _updateQuery(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null,
    string|null $where = null
) : PicoDatabaseQueryBuilder
{
}

Description

Prepares an update query without executing it.

This method constructs an update query using the specified table information and filtering criteria, returning the query builder for further modifications.

Parameters

$info

The table information. If null, fetched internally.

$queryBuilder

The query builder. If null, created internally.

$where

The where clause for the query. If null, fetched internally.

Return

PicoDatabaseQueryBuilder

The query builder with the update query prepared.

Throws

InvalidFilterException

If the provided filter is invalid.

EntityException

If an error occurs while preparing the query.

118. delete

Declaration

public function delete() : PDOStatement
{
}

Description

Deletes a record from the database.

This method constructs and executes a delete query to remove a record from the specified table based on the provided filtering criteria.

Return

PDOStatement

The executed delete statement.

Throws

EntityException

If an error occurs during the deletion process.

119. deleteQuery

Declaration

public function deleteQuery() : PicoDatabaseQueryBuilder
{
}

Description

Prepares a delete query without executing it.

This method constructs a delete query using the specified table information and filtering criteria without executing it, allowing for further modifications.

Return

PicoDatabaseQueryBuilder

The query builder with the delete query prepared.

Throws

EntityException

If an error occurs while preparing the query.

120. _delete

Declaration

private function _delete(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null,
    string|null $where = null
) : PDOStatement
{
}

Description

Deletes a record from the database based on primary keys.

This method constructs and executes a delete query using the provided table information and filtering criteria.

Parameters

$info

The table information. If null, fetched internally.

$queryBuilder

The query builder. If null, created internally.

$where

The where clause for the query. If null, fetched internally.

Return

PDOStatement

The executed delete statement.

121. _deleteQuery

Declaration

private function _deleteQuery(
    PicoTableInfo|null $info = null,
    PicoDatabaseQueryBuilder|null $queryBuilder = null,
    string|null $where = null
) : PicoDatabaseQueryBuilder
{
}

Description

Prepares a delete query without executing it.

This method constructs a delete query using the specified table information and filtering criteria, returning the query builder for further modifications.

Parameters

$info

The table information. If null, fetched internally.

$queryBuilder

The query builder. If null, created internally.

$where

The where clause for the query. If null, fetched internally.

Return

PicoDatabaseQueryBuilder

The query builder with the delete query prepared.

Throws

InvalidFilterException

If the provided filter is invalid.

EntityException

If an error occurs while preparing the query.

122. whereWithSpecification

Declaration

public function whereWithSpecification(
    PicoSpecification $specification
) : PicoDatabasePersistenceExtended
{
}

Description

Retrieves a MagicObject with a WHERE specification.

This method creates a new instance of PicoDatabasePersistenceExtended and configures it with a WHERE clause derived from the provided specification.

Parameters

$specification

The specification used to define the WHERE clause.

Return

PicoDatabasePersistenceExtended

The configured persistence object with the WHERE clause.

123. isArray

Declaration

public static function isArray(
    mixed $value
) : bool
{
}

Description

Checks if the given value is an array.

This method verifies whether the provided value is set and is an array.

Parameters

$value

The value to be checked.

Return

bool

True if the value is an array, false otherwise.

124. isNotEmpty

Declaration

public static function isNotEmpty(
    mixed $input
) : bool
{
}

Description

Check if the given input is not empty.

This function determines if the provided input is set and not empty, returning true if it contains a non-empty value, and false otherwise.

Parameters

$input

The input value to check.

Return

bool

True if the input is not empty, false otherwise.

125. getTimeZoneOffset

Declaration

public function getTimeZoneOffset() : string
{
}

Description

Get the timezone offset for the current session, represented in the format '+hh:mm' or '-hh:mm'.

Return

string
126. setTimeZoneOffset

Declaration

public function setTimeZoneOffset(
    string $timeZoneOffset
) : self
{
}

Description

Set the timezone offset for the current session, represented in the format '+hh:mm' or '-hh:mm'.

Parameters

$timeZoneOffset

The timezone offset for the current session, represented in the format '+hh:mm' or '-hh:mm'.

Return

self
127. getTimeZoneOffsetSystem

Declaration

public function getTimeZoneOffsetSystem() : string
{
}

Description

Get the system's timezone offset in the format '+hh:mm' or '-hh:mm'.

This method returns the system's timezone offset, which is stored as a string in the format of hours and minutes (e.g., '+07:00', '-03:00').

Return

string

The system's timezone offset.

128. setTimeZoneOffsetSystem

Declaration

public function setTimeZoneOffsetSystem(
    string $timeZoneOffsetSystem
) : self
{
}

Description

Set the system's timezone offset in the format '+hh:mm' or '-hh:mm'.

This method sets the system's timezone offset, which should be provided as a string in the format of hours and minutes (e.g., '+07:00', '-03:00').

Parameters

$timeZoneOffsetSystem

The timezone offset to set for the system.

Return

self

Returns the current instance for method chaining.

129. getTimeZone

Declaration

public function getTimeZone() : string
{
}

Description

Get the timezone used for time-related operations within the session.

This method returns the timezone identifier (e.g., 'Asia/Jakarta') that is set for the current session and is used for all time-related operations.

Return

string

The timezone identifier for the current session (e.g., 'Asia/Jakarta').

130. setTimeZone

Declaration

public function setTimeZone(
    string $timeZone
) : self
{
}

Description

Set the timezone used for time-related operations within the session.

This method sets the timezone identifier (e.g., 'Asia/Jakarta') to be used for all time-related operations in the current session.

Parameters

$timeZone

The timezone identifier to be used for time-related operations (e.g., 'Asia/Jakarta').

Return

self

Returns the current instance for method chaining.

131. getTimeZoneSystem

Declaration

public function getTimeZoneSystem() : string
{
}

Description

Get the timezone typically used for system-level time settings.

This method returns the system's timezone identifier (e.g., 'Europe/London') which is generally used for system-level time settings and configurations.

Return

string

The system's timezone identifier (e.g., 'Europe/London').

132. setTimeZoneSystem

Declaration

public function setTimeZoneSystem(
    string $timeZoneSystem
) : self
{
}

Description

Set the timezone typically used for system-level time settings.

This method sets the system's timezone identifier (e.g., 'Europe/London') that is typically used for system configurations and time settings.

Parameters

$timeZoneSystem

The timezone identifier to be used for system-level time settings (e.g., 'Europe/London').

Return

self

Returns the current instance for method chaining.

MagicObject\Database\PicoDatabasePersistenceExtended

Declaration

class PicoDatabasePersistenceExtended extends MagicObject\Database\PicoDatabasePersistence { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Database persistence extended

This class extends the functionality of the PicoDatabasePersistence by adding dynamic property setting through magic methods and enhanced record selection capabilities.

Properties

1. map

Declaration

private $map = array();

Description

@var array An array of property-value pairs where each entry contains the name of a property and its corresponding value.

2. database

Declaration

protected PicoDatabase $database;

Description

Database connection

3. object

Declaration

protected MagicObject $object;

Description

Object

4. className

Declaration

protected string $className = '';

Description

Class name

5. joinColumMaps

Declaration

protected PicoJoinMap[] $joinColumMaps = array();

Description

Join map

6. whereIsDefinedFirst

Declaration

protected boolean $whereIsDefinedFirst = false;

Description

Flag that WHERE is defined first

7. whereStr

Declaration

protected string $whereStr;

Description

WHERE saved on previous

8. specification

Declaration

protected PicoSpecification $specification;

Description

Specification

9. pageable

Declaration

protected PicoPageable $pageable;

Description

Pageable

10. sortable

Declaration

protected PicoSortable $sortable;

Description

Sortable

Methods

1. set

Declaration

public function set(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Sets a property value and adds it to the internal map.

This method sets a value to a property of the associated object and adds the property name and value to an internal map for further processing.

Parameters

$propertyName

The name of the property to set.

$propertyValue

The value to assign to the property.

Return

self

Returns the current instance for method chaining.

2. addToMap

Declaration

private function addToMap(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Adds the property name and value to the internal map.

This method adds the given property name and value as an entry in the internal $map array.

Parameters

$propertyName

The name of the property.

$propertyValue

The value of the property.

Return

self

Returns the current instance for method chaining.

3. __call

Declaration

public function __call(
    string $method,
    mixed[] $params
) : $this
{
}

Description

Magic method to handle undefined methods for setting properties.

This method dynamically handles method calls that start with "set". It allows setting properties of the object in a more flexible way, using a consistent naming convention.

Supported dynamic method:

  • set<PropertyName>: Sets the value of the specified property.
    • If the property name follows "set", the method extracts the property name and assigns the provided value to it.
    • If no value is provided, it sets the property to null.
    • Example: $obj->setFoo($value) sets the property foo to $value.

Parameters

$method

The name of the method that was called.

$params

The parameters passed to the method, expected to be an array.

Return

$this

Returns the current instance for method chaining.

4. currentDatabase

Declaration

private function currentDatabase(
    MagicObject $entity
) : PicoDatabase
{
}

Description

Get the current database for the specified entity.

This method retrieves the database connection associated with the provided entity. If the entity does not have an associated database or if the connection is not valid, it defaults to the object's primary database connection.

Parameters

$entity

The entity for which to get the database.

Return

PicoDatabase

The database connection for the entity.

7. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only. It converts the object to a JSON string that represents the current state of the object, including the 'where' specification and the 'set' mapping, making it easier to inspect the internal data during development.

Return

string

The JSON string representation of the object, containing:

MagicObject\Database\PicoDatabaseQueryBuilder

Declaration

class PicoDatabaseQueryBuilder { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseQueryBuilder

A query builder for constructing SQL statements programmatically. This class facilitates the creation of various SQL commands including SELECT, INSERT, UPDATE, and DELETE, while managing database-specific nuances.

Example:

 <?php
 $id = 100;
 $db = new PicoDatabase($credentials);
 $db->connect();
 $query = new PicoDatabaseQueryBuilder($db);
 $query
     ->select("*")
     ->from("client")
     ->where("client_id = ?", $id)
 ;
 $data = $db->fetch($query);
 echo $data['client_id']."\r\n"; // Client ID
 echo $data['name']."\r\n"; // Client name 

Properties

1. buffer

Declaration

private string $buffer = '';

Description

Buffer to hold the constructed SQL query.

2. limitOffset

Declaration

private bool $limitOffset = false;

Description

Indicates whether limit and offset have been set.

3. limit

Declaration

private int $limit = 0;

Description

The limit for the number of results.

4. offset

Declaration

private int $offset = 0;

Description

The offset for the results.

5. databaseType

Declaration

private string $databaseType = 'mysql';

Description

The type of database being used.

6. hasValues

Declaration

private bool $hasValues = false;

Description

Flag indicating if values have been set.

Methods

1. __construct

Declaration

public function __construct(
    PicoDatabase|string $databaseType
)
{
}

Description

Constructor for PicoDatabaseQueryBuilder.

Parameters

$databaseType

The database type or an instance of PicoDatabase.

2. getDatabaseType

Declaration

public function getDatabaseType() : string
{
}

Description

Get the value of the database type.

Return

string

The database type.

3. isMySql

Declaration

public function isMySql() : bool
{
}

Description

Check if the database type is MySQL or MariaDB.

Return

bool

True if the database type is MySQL or MariaDB, false otherwise.

4. isPgSql

Declaration

public function isPgSql() : bool
{
}

Description

Check if the database type is PostgreSQL.

Return

bool

True if the database type is PostgreSQL, false otherwise.

5. isSqlite

Declaration

public function isSqlite() : bool
{
}

Description

Check if the database type is SQLite.

Return

bool

True if the database type is SQLite, false otherwise.

6. isSqlServer

Declaration

public function isSqlServer() : bool
{
}

Description

Check if the database type is SQL Server.

Return

bool

True if the database type is SQLite, false otherwise.

7. newQuery

Declaration

public function newQuery() : self
{
}

Description

Initialize a new SQL query by resetting the buffer, limit, and offset.

Return

self

Returns the current instance for method chaining.

8. insert

Declaration

public function insert() : self
{
}

Description

Create an insert statement.

Return

self

Returns the current instance for method chaining.

9. into

Declaration

public function into(
    string $query
) : self
{
}

Description

Specify the table to insert into.

Parameters

$query

The name of the table.

Return

self

Returns the current instance for method chaining.

10. fields

Declaration

public function fields(
    mixed $query
) : self
{
}

Description

Specify the fields to insert values into.

Parameters

$query

The field names (string or array).

Return

self

Returns the current instance for method chaining.

11. values

Declaration

public function values(
    mixed $query
) : self
{
}

Description

Specify the values to be inserted.

Parameters

$query

The values to insert (string, array, or multiple parameters).

Return

self

Returns the current instance for method chaining.

12. select

Declaration

public function select(
    string $query = ''
) : self
{
}

Description

Create a select statement.

Parameters

$query

The fields to select (optional).

Return

self

Returns the current instance for method chaining.

13. alias

Declaration

public function alias(
    string $query
) : self
{
}

Description

Create an alias for a field or table.

Parameters

$query

The alias to use.

Return

self

Returns the current instance for method chaining.

14. delete

Declaration

public function delete() : self
{
}

Description

Create a delete statement.

Return

self

Returns the current instance for method chaining.

15. from

Declaration

public function from(
    string $query
) : self
{
}

Description

Specify the source table for the query.

Parameters

$query

The name of the table.

Return

self

Returns the current instance for method chaining.

16. join

Declaration

public function join(
    string $query
) : self
{
}

Description

Create a join statement.

Parameters

$query

The join details.

Return

self

Returns the current instance for method chaining.

17. innerJoin

Declaration

public function innerJoin(
    string $query
) : self
{
}

Description

Create an inner join statement.

Parameters

$query

The join details.

Return

self

Returns the current instance for method chaining.

18. outerJoin

Declaration

public function outerJoin(
    string $query
) : self
{
}

Description

Create an outer join statement.

Parameters

$query

The join details.

Return

self

Returns the current instance for method chaining.

19. leftOuterJoin

Declaration

public function leftOuterJoin(
    string $query
) : self
{
}

Description

Create a left outer join statement.

Parameters

$query

The join details.

Return

self

Returns the current instance for method chaining.

20. leftJoin

Declaration

public function leftJoin(
    string $query
) : self
{
}

Description

Create a left join statement.

Parameters

$query

The join details.

Return

self

Returns the current instance for method chaining.

21. rightJoin

Declaration

public function rightJoin(
    string $query
) : self
{
}

Description

Create a right join statement.

Parameters

$query

The join details.

Return

self

Returns the current instance for method chaining.

22. on

Declaration

public function on(
    mixed $query
) : self
{
}

Description

Create an ON statement for JOIN operations.

Parameters

$query

The join condition(s).

Return

self

Returns the current instance for method chaining.

23. update

Declaration

public function update(
    string $query
) : self
{
}

Description

Create an UPDATE statement for a specified table.

Parameters

$query

The name of the table to update.

Return

self

Returns the current instance for method chaining.

24. set

Declaration

public function set(
    mixed $query
) : self
{
}

Description

Specify the fields and values to set in the UPDATE statement.

Parameters

$query

The field(s) and value(s) to set.

Return

self

Returns the current instance for method chaining.

25. where

Declaration

public function where(
    string $query
) : self
{
}

Description

Create a WHERE statement for filtering results.

Parameters

$query

The condition(s) for the WHERE clause.

Return

self

Returns the current instance for method chaining.

26. createMatchedValue

Declaration

public function createMatchedValue(
    array $args
) : string
{
}

Description

Create a matched value string from the given arguments.

Parameters

$args

The arguments to match.

Return

string

The formatted string.

27. createInsertQuery

Declaration

public function createInsertQuery(
    string $table,
    array $data
) : string
{
}

Description

Create an INSERT query for a specified table.

Parameters

$table

The name of the table.

$data

The data to be inserted.

Return

string

The constructed INSERT query.

28. createUpdateQuery

Declaration

public function createUpdateQuery(
    string $table,
    array $data,
    array $primaryKey
) : string
{
}

Description

Create an UPDATE query for a specified table.

Parameters

$table

The name of the table.

$data

The data to be updated.

$primaryKey

The primary keys for the update condition.

Return

string

The constructed UPDATE query.

29. having

Declaration

public function having(
    string $query
) : self
{
}

Description

Create a HAVING statement for filtering aggregated results.

Parameters

$query

The condition(s) for the HAVING clause.

Return

self

Returns the current instance for method chaining.

30. orderBy

Declaration

public function orderBy(
    string $query
) : self
{
}

Description

Create an ORDER BY statement for sorting results.

Parameters

$query

The field(s) to order by.

Return

self

Returns the current instance for method chaining.

31. groupBy

Declaration

public function groupBy(
    string $query
) : self
{
}

Description

Create a GROUP BY statement for grouping results.

Parameters

$query

The field(s) to group by.

Return

self

Returns the current instance for method chaining.

32. limit

Declaration

public function limit(
    int $limit
) : self
{
}

Description

Set a limit on the number of results returned.

Parameters

$limit

The maximum number of results.

Return

self

Returns the current instance for method chaining.

33. offset

Declaration

public function offset(
    int $offset
) : self
{
}

Description

Set an offset for the results returned.

Parameters

$offset

The offset from the start of the result set.

Return

self

Returns the current instance for method chaining.

34. lockTables

Declaration

public function lockTables(
    string $tables
) : string|null
{
}

Description

Create a LOCK TABLES statement for database locking.

Parameters

$tables

Comma-separated table names to lock.

Return

string|null

The LOCK TABLES statement or null if not supported.

35. unlockTables

Declaration

public function unlockTables() : string|null
{
}

Description

Create an UNLOCK TABLES statement to release table locks.

Return

string|null

The UNLOCK TABLES statement or null if not supported.

36. startTransaction

Declaration

public function startTransaction() : string|null
{
}

Description

Create a START TRANSACTION statement for initiating a transaction.

Return

string|null

The START TRANSACTION statement or null if not supported.

37. commit

Declaration

public function commit() : string|null
{
}

Description

Create a COMMIT statement to finalize a transaction.

Return

string|null

The COMMIT statement or null if not supported.

38. rollback

Declaration

public function rollback() : string|null
{
}

Description

Create a ROLLBACK statement to revert a transaction.

Return

string|null

The ROLLBACK statement or null if not supported.

39. escapeSQL

Declaration

public function escapeSQL(
    string $query
) : string
{
}

Description

Escape special characters in a SQL string.

This method escapes special characters in a SQL query string to prevent SQL injection and ensure proper execution across different database systems. It handles various database types (SQLite, MySQL/MariaDB, PostgreSQL, and SQL Server) by applying database-specific escaping techniques:

  • For MySQL/MariaDB, it uses addslashes for special characters and escapes newline characters.
  • For PostgreSQL and SQLite, it uses a custom quote replacement function and escapes newline characters.
  • For SQL Server, it doubles the single quote characters (') to escape them.

Parameters

$query

The SQL query string to escape. This should be a valid

Return

string

The escaped SQL query string. This result can be safely used

40. escapeValue

Declaration

public function escapeValue(
    mixed $value
) : string
{
}

Description

Escape a value for SQL queries.

This method safely escapes different types of values (null, strings, booleans, numeric values, arrays, and objects) to ensure that they can be safely used in SQL queries. It prevents SQL injection by escaping potentially dangerous characters in string values and converts arrays or objects to their JSON representation.

Parameters

$value

The value to be escaped. Can be null, string, boolean,

Return

string

The escaped value. This will be a string representation

41. escapedJSONValues

Declaration

public function escapedJSONValues(
    mixed $values
) : string
{
}

Description

Escapes the JSON-encoded values.

This function takes an input value, encodes it into JSON format, and then escapes the resulting JSON string to ensure it is safe for use (e.g., preventing injection or special character issues).

Parameters

$values

The input values to be encoded into JSON and escaped.

Return

string

The escaped JSON string.

42. createBoolean

Declaration

public function createBoolean(
    mixed $value
) : string
{
}

Description

Convert a value to its boolean representation for SQL.

For SQLite, returns '1' for true and '0' for false. For other databases, returns 'TRUE' for true and 'FALSE' for false.

Parameters

$value

The value to be converted.

Return

string

The boolean representation as a string.

43. implodeValues

Declaration

public function implodeValues(
    array $values
) : string
{
}

Description

Convert an array to a comma-separated list of escaped values.

Parameters

$values

The array of values.

Return

string

The comma-separated list.

44. executeFunction

Declaration

public function executeFunction(
    string $name,
    string $params
) : string|null
{
}

Description

Create a statement to execute a function.

Parameters

$name

The name of the function to execute.

$params

The parameters for the function.

Return

string|null

The SQL statement to execute the function or null if not supported.

45. executeProcedure

Declaration

public function executeProcedure(
    string $name,
    string $params
) : string|null
{
}

Description

Create a statement to execute a stored procedure.

Parameters

$name

The name of the procedure to execute.

$params

The parameters for the procedure.

Return

string|null

The SQL statement to execute the procedure or null if not supported.

46. lastID

Declaration

public function lastID() : self
{
}

Description

Create a statement to retrieve the last inserted ID.

Return

self

Returns the current instance for method chaining.

47. currentDate

Declaration

public function currentDate() : string|null
{
}

Description

Create a statement to get the current date.

Return

string|null

The SQL statement for the current date or null if not supported.

48. currentTime

Declaration

public function currentTime() : string|null
{
}

Description

Create a statement to get the current time.

Return

string|null

The SQL statement for the current time or null if not supported.

49. currentTimestamp

Declaration

public function currentTimestamp() : string|null
{
}

Description

Create a statement to get the current timestamp.

Return

string|null

The SQL statement for the current timestamp or null if not supported.

50. now

Declaration

public function now(
    int $precision = 0
) : string
{
}

Description

Create a NOW statement for the current time with optional precision.

Parameters

$precision

The decimal precision of seconds (default is 0).

Return

string

The NOW statement with the specified precision.

51. replaceQuote

Declaration

public function replaceQuote(
    string $query
) : string
{
}

Description

Replace single quotes with double single quotes in a SQL string for escaping.

Parameters

$query

The SQL query string to modify.

Return

string

The modified SQL query string.

52. addQueryParameters

Declaration

public function addQueryParameters(
    string $query
) : string
{
}

Description

Add query parameters to a SQL statement.

Parameters

$query

The SQL query string.

Return

string

The constructed SQL query with parameters.

53. addPaginationAndSorting

Declaration

public function addPaginationAndSorting(
    string $queryString,
    PicoPageable|null $pageable,
    PicoSortable|null $sortable
) : string
{
}

Description

Adds pagination and sorting clauses to a native query string.

This function appends the appropriate ORDER BY and LIMIT $limit OFFSET $offset or LIMIT $offset, $limit clauses to the provided SQL query string based on the given pagination and sorting parameters. It supports various database management systems (DBMS) and adjusts the query syntax accordingly (e.g., for PostgreSQL, SQLite, MySQL, MariaDB, etc.).

Parameters

$queryString

The original SQL query string to which pagination and sorting will be added.

$pageable

The pagination parameters, or null if pagination is not required.

$sortable

The sorting parameters, or null if sorting is not required.

Return

string

The modified SQL query string with added pagination and sorting clauses.

54. toString

Declaration

public function toString() : string
{
}

Description

Converts the current object to a string representation.

This method casts the current object to a string. It relies on the magic method __toString() to provide a meaningful string representation of the object.

Return

string

The string representation of the object.

55. __toString

Declaration

public function __toString() : string
{
}

Description

Magic method that converts the object to a string representation.

This method generates a SQL query string based on the object's buffer and the limit/offset properties. The exact SQL syntax depends on the database type being used (MySQL, PostgreSQL, SQLite, or SQL Server).

Return

string

The generated SQL query string with pagination (if applicable).

MagicObject\Database\PicoDatabaseQueryTemplate

Declaration

class PicoDatabaseQueryTemplate { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseQueryTemplate

This class represents a query template or builder that can either hold a pre-defined query template (as a string) or an instance of a query builder (PicoDatabaseQueryBuilder). It is designed to facilitate the construction and conversion of queries to a string format, either directly or through a query builder.

Properties

1. template

Declaration

private string $template;

Description

The query template as a string.

This property holds the template for a database query in string format, or null if no template is provided.

2. builder

Declaration

private PicoDatabaseQueryBuilder $builder;

Description

The query builder instance.

This property holds an instance of PicoDatabaseQueryBuilder, which is used to build and manipulate database queries programmatically.

Methods

1. __construct

Declaration

public function __construct(
    PicoDatabaseQueryBuilder|string|null $query
)
{
}

Description

PicoDatabaseQueryTemplate constructor.

The constructor accepts either a query builder object or a query template string. It initializes the appropriate property based on the type of the provided argument.

Parameters

$query

The query builder object or query template string.

2. __toString

Declaration

public function __toString() : string
{
}

Description

Converts the object to a string representation.

This method returns the string representation of the query. If a query builder instance is set, it will return the string representation of the builder. If a query template string is provided, it will return that template string. If neither is set, it will return an empty string.

Return

string

The string representation of the query, either from the builder or template.

MagicObject\Database\PicoDatabaseStructure

Declaration

class PicoDatabaseStructure { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Represents the structure of a database table.

This class is used to manage and generate the structure of a database table based on annotations defined in a MagicObject class. It provides functionality to create SQL CREATE TABLE statements and retrieve metadata about the table, including its columns, primary keys, and nullable fields.

It uses annotations such as @Table to specify the table name and @Column to define column properties in a class. The class can automatically generate SQL statements for creating a table and its columns based on this metadata.

The class also provides utility methods for retrieving table information, such as column definitions, and for handling column attributes like nullable, primary, and notnull.

Constants

const ANNOTATION_TABLE = "Table";
const ANNOTATION_COLUMN = "Column";
const ANNOTATION_ID = "Id";
const KEY_NAME = "name";
const KEY_TYPE = "type";
const KEY_NULL = "null";
const KEY_NOT_NULL = "notnull";
const KEY_NULLABLE = "nullable";
const KEY_PRIMARY = "primary";

Properties

1. object

Declaration

private MagicObject $object;

Description

The associated MagicObject instance.

2. className

Declaration

private string $className = '';

Description

The name of the class representing the table.

Methods

1. __construct

Declaration

public function __construct(
    MagicObject $object
)
{
}

Description

Constructor to initialize the PicoDatabaseStructure with a MagicObject.

Parameters

$object

The MagicObject representing the database structure.

2. showCreateTable

Declaration

public function showCreateTable(
    string $databaseType,
    string|null $tableName = null
) : string
{
}

Description

Generates a CREATE TABLE statement based on the object's metadata.

Parameters

$databaseType

The type of database (e.g., MySQL, MariaDB).

$tableName

Optional name of the table. If not provided, it will be inferred.

Return

string

The SQL CREATE TABLE statement.

Throws

MandatoryTableNameException

If no table name is provided and cannot be inferred.

3. showCreateTableByType

Declaration

private function showCreateTableByType(
    string $databaseType,
    PicoTableInfo $info
) : string
{
}

Description

Generates the CREATE TABLE syntax based on the database type and table information.

Parameters

$databaseType

The type of database (e.g., MySQL).

$info

The table information containing column definitions.

Return

string

The SQL column definitions for the CREATE TABLE statement.

4. nullable

Declaration

private function nullable(
    mixed $nullable
) : string
{
}

Description

Returns the NULL/NOT NULL declaration based on the nullable setting.

Parameters

$nullable

Indicates if the column is nullable.

Return

string

The corresponding NULL or NOT NULL declaration.

5. parseKeyValue

Declaration

private function parseKeyValue(
    PicoAnnotationParser $reflexClass,
    string $queryString,
    string $parameter
) : array
{
}

Description

Parses a key-value string from an annotation.

Parameters

$reflexClass

The reflection of the class containing the annotation.

$queryString

The string to be parsed.

$parameter

The parameter name for error reporting.

Return

array

The parsed key-value pairs.

Throws

InvalidAnnotationException

If the annotations are invalid or cannot be parsed.

6. getObjectInfo

Declaration

public function getObjectInfo() : PicoTableInfo
{
}

Description

Retrieves metadata about the object, including table name and column definitions.

Return

PicoTableInfo

An instance containing the table name and column information.

MagicObject\Database\PicoDatabaseType

Declaration

class PicoDatabaseType { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseType

Defines constants for various database types supported by the MagicObject framework. This class provides a centralized reference to these types, enhancing code clarity and maintainability.

Supported database types include:

  • MySQL
  • MariaDB
  • PostgreSQL
  • SQLite
  • SQL Server

Constants

const DATABASE_TYPE_MYSQL = "mysql";
const DATABASE_TYPE_MARIADB = "mariadb";
const DATABASE_TYPE_POSTGRESQL = "postgresql";
const DATABASE_TYPE_PGSQL = "pgsql";
const DATABASE_TYPE_SQLITE = "sqlite";
const DATABASE_TYPE_SQLSERVER = "sqlsrv";

MagicObject\Database\PicoDataComparation

Declaration

class PicoDataComparation { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDataComparation

This class provides various comparison operations for use in database queries. It allows the creation of comparison objects that can be utilized to compare values against specified criteria, facilitating flexible and expressive database querying.

The class supports a variety of comparison operators such as equality, inequality, inclusion, and range comparisons. Each operator can be applied to values of various types, including strings, booleans, and numbers.

Constants

const EQUALS = "=";
const NOT_EQUALS = "!=";
const IN = "in";
const BETWEEN = "between";
const NOT_IN = "not in";
const IS = "is";
const IS_NOT = "is not";
const LIKE = "like";
const NOT_LIKE = "not like";
const LESS_THAN = "<";
const GREATER_THAN = ">";
const LESS_THAN_OR_EQUALS = "<=";
const GREATER_THAN_OR_EQUALS = ">=";
const TYPE_STRING = "string";
const TYPE_BOOLEAN = "boolean";
const TYPE_NUMERIC = "numeric";
const TYPE_NULL = "null";

Properties

1. comparison

Declaration

private string $comparison = '=';

Description

The comparison operator.

2. value

Declaration

private mixed $value;

Description

The value to compare against.

3. type

Declaration

private string $type = 'null';

Description

The type of the value.

Methods

1. equals

Declaration

public static function equals(
    mixed $value
) : self
{
}

Description

Creates a comparison for equality.

Parameters

$value

The value to compare.

Return

self

Returns the current instance for method chaining.

2. notEquals

Declaration

public static function notEquals(
    mixed $value
) : self
{
}

Description

Creates a comparison for inequality.

Parameters

$value

The value to compare.

Return

self

Returns the current instance for method chaining.

3. in

Declaration

public static function in(
    mixed[] $values
) : self
{
}

Description

Creates a comparison for inclusion in a set.

Parameters

$values

The values to compare against.

Return

self

Returns the current instance for method chaining.

4. inRange

Declaration

public static function inRange(
    mixed[] $values
) : self
{
}

Description

Creates a comparison for inclusion within a range.

Parameters

$values

The range boundaries to compare against.

Return

self

Returns the current instance for method chaining.

5. between

Declaration

public static function between(
    mixed $min,
    mixed $max
) : self
{
}

Description

Creates a comparison for values within a specified range.

Parameters

$min

The lower boundary of the range.

$max

The upper boundary of the range.

Return

self

Returns the current instance for method chaining.

6. notIn

Declaration

public static function notIn(
    mixed[] $values
) : self
{
}

Description

Creates a comparison for exclusion from a set.

Parameters

$values

The values to compare against.

Return

self

Returns the current instance for method chaining.

7. like

Declaration

public static function like(
    mixed $value
) : self
{
}

Description

Creates a comparison using the LIKE operator.

Parameters

$value

The value to compare.

Return

self

Returns the current instance for method chaining.

8. notLike

Declaration

public static function notLike(
    mixed $value
) : self
{
}

Description

Creates a comparison using the NOT LIKE operator.

Parameters

$value

The value to compare.

Return

self

Returns the current instance for method chaining.

9. lessThan

Declaration

public static function lessThan(
    mixed $value
) : self
{
}

Description

Creates a comparison for less than.

Parameters

$value

The value to compare.

Return

self

Returns the current instance for method chaining.

10. greaterThan

Declaration

public static function greaterThan(
    mixed $value
) : self
{
}

Description

Creates a comparison for greater than.

Parameters

$value

The value to compare.

Return

self

Returns the current instance for method chaining.

11. lessThanOrEquals

Declaration

public static function lessThanOrEquals(
    mixed $value
) : self
{
}

Description

Creates a comparison for less than or equal to.

Parameters

$value

The value to compare.

Return

self

Returns the current instance for method chaining.

12. greaterThanOrEquals

Declaration

public static function greaterThanOrEquals(
    mixed $value
) : self
{
}

Description

Creates a comparison for greater than or equal to.

Parameters

$value

The value to compare.

Return

self

Returns the current instance for method chaining.

13. __construct

Declaration

public function __construct(
    mixed $value,
    string $comparison = '='
)
{
}

Description

Constructor for PicoDataComparation.

Parameters

$value

The value to compare.

$comparison

The comparison operator.

14. _equals

Declaration

private function _equals() : string
{
}

Description

Returns the appropriate equals operator based on the value's state.

If the value is null or of type null, returns the IS operator; otherwise, returns the standard equals operator.

Return

string

The equals operator.

15. _notEquals

Declaration

private function _notEquals() : string
{
}

Description

Returns the appropriate not equals operator based on the value's state.

If the value is null or of type null, returns the IS NOT operator; otherwise, returns the standard not equals operator.

Return

string

The not equals operator.

16. _lessThan

Declaration

private function _lessThan() : string
{
}

Description

Returns the less than operator.

Return

string

The less than operator.

17. _greaterThan

Declaration

private function _greaterThan() : string
{
}

Description

Returns the greater than operator.

Return

string

The greater than operator.

18. _lessThanOrEquals

Declaration

private function _lessThanOrEquals() : string
{
}

Description

Returns the less than or equals operator.

Return

string

The less than or equals operator.

19. _greaterThanOrEquals

Declaration

private function _greaterThanOrEquals() : string
{
}

Description

Returns the greater than or equals operator.

Return

string

The greater than or equals operator.

20. getComparison

Declaration

public function getComparison() : string
{
}

Description

Determines the comparison operator based on the current value and its type.

Return

string

The comparison operator corresponding to the current state.

21. getValue

Declaration

public function getValue() : mixed
{
}

Description

Gets the value being compared.

Return

mixed

The value that is currently being compared.

MagicObject\Database\PicoEntityField

Declaration

class PicoEntityField { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing an entity field in a database.

This class encapsulates information about an entity field, including its associated entity, field name, and any parent field relationships.

Properties

1. entity

Declaration

private string $entity;

Description

The associated entity.

2. objectName

Declaration

private string $objectName;

Description

The object name associated with the field.

3. field

Declaration

private string $field;

Description

The field name.

4. parentField

Declaration

private string $parentField;

Description

The parent field name.

5. functionFormat

Declaration

private string $functionFormat = '%s';

Description

The function format for the field.

Methods

1. __construct

Declaration

public function __construct(
    string $fieldRaw,
    PicoTableInfo|null $info = null
)
{
}

Description

Constructor for PicoEntityField.

Parameters

$fieldRaw

The raw field input.

$info

Table information (optional).

2. getEntity

Declaration

public function getEntity() : string|null
{
}

Description

Get the associated entity.

Return

string|null

The entity name.

3. getField

Declaration

public function getField() : string|null
{
}

Description

Get the field name.

Return

string|null

The field name.

4. getParentField

Declaration

public function getParentField() : string|null
{
}

Description

Get the parent field name.

Return

string|null

The parent field name.

5. getFunctionFormat

Declaration

public function getFunctionFormat() : string
{
}

Description

Get the function format for the field.

Return

string

The function format.

6. extractField

Declaration

public function extractField(
    string $fieldRaw
) : string
{
}

Description

Extract the field name from a raw field input.

If the input contains a function, it extracts the field name and updates the function format.

Parameters

$fieldRaw

The raw field input.

Return

string

The extracted field name.

MagicObject\Database\PicoEntityLabel

Declaration

class PicoEntityLabel { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class to manage entity labels and their annotations.

Provides methods to retrieve and filter entity metadata, including labels, columns, and other attributes.

Constants

const ANNOTATION_TABLE = "Table";
const ANNOTATION_LABEL = "label";
const ANNOTATION_COLUMN = "Column";
const ANNOTATION_JOIN_COLUMN = "JoinColumn";
const ANNOTATION_VAR = "var";
const ANNOTATION_ID = "Id";
const ANNOTATION_GENERATED_VALUE = "GeneratedValue";
const ANNOTATION_NOT_NULL = "NotNull";
const ANNOTATION_DEFAULT_COLUMN = "DefaultColumn";
const KEY_NAME = "name";
const KEY_NULL = "null";
const KEY_NOT_NULL = "notnull";
const KEY_NULLABLE = "nullable";
const KEY_INSERTABLE = "insertable";
const KEY_UPDATABLE = "updatable";
const KEY_STRATEGY = "strategy";
const KEY_GENERATOR = "generator";
const KEY_PROPERTY_TYPE = "propertyType";
const KEY_VALUE = "value";
const KEY_ENTITY_OBJECT = "entityObject";
const VALUE_TRUE = "true";
const VALUE_FALSE = "false";

Properties

1. className

Declaration

private string $className;

Description

The class name of the entity.

2. langs

Declaration

private string[] $langs;

Description

Supported languages for labels.

Methods

1. __construct

Declaration

public function __construct(
    MagicObject $object,
    string[] $langs
)
{
}

Description

Constructor for the PicoEntityLabel class.

Parameters

$object

The entity object.

$langs

Supported languages.

2. getMap

Declaration

public function getMap(
    string|null $lang = null
) : array|null
{
}

Description

Get the mapping of labels based on the specified language.

Parameters

$lang

The language to filter the labels by.

Return

array|null

The filtered labels, or null if the language is not supported.

3. filter

Declaration

private function filter(
    array $merged,
    string|null $lang
) : array|null
{
}

Description

Filter the merged labels based on the specified language.

Parameters

$merged

Merged array of labels.

$lang

The language to filter by.

Return

array|null

The filtered labels, or null if the language is not supported.

4. parseKeyValue

Declaration

private function parseKeyValue(
    PicoAnnotationParser $reflexClass,
    string $queryString,
    string $parameter
) : array
{
}

Description

Parse a key-value string from the annotation parser.

Parameters

$reflexClass

Reflection class for the entity.

$queryString

The query string to parse.

$parameter

The parameter name.

Return

array

The parsed key-value pairs.

Throws

InvalidAnnotationException

If the annotations are invalid or cannot be parsed.

5. getObjectInfo

Declaration

public function getObjectInfo() : stdClass
{
}

Description

Get object information, including metadata about labels, columns, and more.

Return

stdClass

An object containing entity metadata.

MagicObject\Database\PicoJoinMap

Declaration

class PicoJoinMap { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a join mapping in a database.

Contains information about how an entity is joined with another table.

Properties

1. propertyName

Declaration

private string $propertyName;

Description

The property name in the entity.

2. columnName

Declaration

private string $columnName;

Description

The column name in the join table.

3. entity

Declaration

private string $entity;

Description

The name of the entity being joined.

4. joinTable

Declaration

private string $joinTable;

Description

The name of the join table.

5. joinTableAlias

Declaration

private string $joinTableAlias;

Description

The alias for the join table.

Methods

1. __construct

Declaration

public function __construct(
    string $propertyName,
    string $columnName,
    string $entity,
    string $joinTable,
    string $joinTableAlias
)
{
}

Description

Constructor for PicoJoinMap.

Parameters

$propertyName

The property name.

$columnName

The column name.

$entity

The entity name.

$joinTable

The join table name.

$joinTableAlias

The join table alias.

2. getPropertyName

Declaration

public function getPropertyName() : string
{
}

Description

Get the property name.

Return

string

The property name.

3. getColumnName

Declaration

public function getColumnName() : string
{
}

Description

Get the column name.

Return

string

The column name.

4. getEntity

Declaration

public function getEntity() : string
{
}

Description

Get the entity name.

Return

string

The entity name.

5. getJoinTable

Declaration

public function getJoinTable() : string
{
}

Description

Get the join table name.

Return

string

The join table name.

6. getJoinTableAlias

Declaration

public function getJoinTableAlias() : string
{
}

Description

Get the join table alias.

Return

string

The join table alias.

7. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

MagicObject\Database\PicoLimit

Declaration

class PicoLimit { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoLimit

This class provides functionality to manage pagination in database queries by setting limits and offsets for record retrieval.

Properties

1. limit

Declaration

private int $limit = 0;

Description

The maximum number of records to retrieve.

2. offset

Declaration

private int $offset = 0;

Description

The number of records to skip before starting to collect the result set.

Methods

1. __construct

Declaration

public function __construct(
    int $offset = 0,
    int $limit = 0
)
{
}

Description

Constructor to initialize offset and limit.

Parameters

$offset

The number of records to skip. Default is 0.

$limit

The maximum number of records to retrieve. Default is 0.

2. nextPage

Declaration

public function nextPage() : self
{
}

Description

Increment the offset to retrieve the next page of records.

This method adjusts the offset based on the current limit, allowing for the retrieval of the next set of records in a paginated result.

Return

self

Returns the current instance for method chaining.

3. previousPage

Declaration

public function previousPage() : self
{
}

Description

Decrement the offset to retrieve the previous page of records.

This method adjusts the offset back, ensuring it does not fall below zero, thus allowing navigation to the previous set of records.

Return

self

Returns the current instance for method chaining.

4. getLimit

Declaration

public function getLimit() : int
{
}

Description

Get the maximum number of records to retrieve.

Return

int
5. setLimit

Declaration

public function setLimit(
    int $limit
) : self
{
}

Description

Set the maximum number of records to retrieve.

This method ensures that the limit is at least 1.

Parameters

$limit

The maximum number of records.

Return

self

Returns the current instance for method chaining.

6. getOffset

Declaration

public function getOffset() : int
{
}

Description

Get the current offset for record retrieval.

Return

int
7. setOffset

Declaration

public function setOffset(
    int $offset
) : self
{
}

Description

Set the number of records to skip before starting to collect the result set.

This method ensures that the offset is not negative.

Parameters

$offset

The number of records to skip.

Return

self

Returns the current instance for method chaining.

8. getPage

Declaration

public function getPage() : PicoPage
{
}

Description

Get information about the current page based on the offset and limit.

This method calculates the current page number and returns a PicoPage object containing the page number and limit.

Return

PicoPage
9. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

MagicObject\Database\PicoPage

Declaration

class PicoPage { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a data page for pagination.

This class provides functionality to manage page numbers and sizes, and to calculate offsets for database queries.

Properties

1. pageNumber

Declaration

private int $pageNumber = 1;

Description

Page number.

2. pageSize

Declaration

private int $pageSize = 1;

Description

Page size (number of items per page).

Methods

1. __construct

Declaration

public function __construct(
    int $pageNumber = 1,
    int $pageSize = 1
)
{
}

Description

Constructor.

Initializes the page number and page size.

Parameters

$pageNumber

Page number (default is 1).

$pageSize

Page size (default is 1).

2. nextPage

Declaration

public function nextPage() : self
{
}

Description

Increase the page number by one.

Return

self

Returns the current instance for method chaining.

3. previousPage

Declaration

public function previousPage() : self
{
}

Description

Decrease the page number by one, ensuring it doesn't go below 1.

Return

self

Returns the current instance for method chaining.

4. getPageNumber

Declaration

public function getPageNumber() : int
{
}

Description

Retrieves the current page number.

Return

int

The current page number.

5. setPageNumber

Declaration

public function setPageNumber(
    int $pageNumber
) : self
{
}

Description

Set the page number.

Parameters

$pageNumber

Page number.

Return

self

Returns the current instance for method chaining.

6. getPageSize

Declaration

public function getPageSize() : int
{
}

Description

Retrieves the page size (number of items per page).

Return

int

The page size.

7. setPageSize

Declaration

public function setPageSize(
    int $pageSize
) : self
{
}

Description

Set the page size.

Parameters

$pageSize

Page size.

Return

self

Returns the current instance for method chaining.

8. getOffset

Declaration

public function getOffset() : int
{
}

Description

Calculates and retrieves the offset for database queries.

The offset is used to determine the starting point for fetching data in paginated queries, based on the current page number and page size.

Return

int

The calculated offset for database queries.

9. getLimit

Declaration

public function getLimit() : PicoLimit
{
}

Description

Calculates the limit and offset for database queries.

Return

PicoLimit

An instance of PicoLimit with the calculated offset and limit.

10. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

MagicObject\Database\PicoPageable

Declaration

class PicoPageable { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Pageable

Properties

1. page

Declaration

private PicoPage $page;

Description

Current page information.

2. sortable

Declaration

private PicoSortable $sortable;

Description

Sortable information.

3. offsetLimit

Declaration

private PicoLimit $offsetLimit;

Description

Offset and limit for database queries.

Methods

1. __construct

Declaration

public function __construct(
    PicoPage|PicoLimit|array|null $page = null,
    PicoSortable|array|null $sortable = null
)
{
}

Description

Constructor for the Pageable class.

This constructor allows initializing a Pageable object with pagination and sorting options. It supports different formats for both page and sortable parameters.

Example 1: Using PicoPage and PicoSortable

 <?php
 $pageable = new Pageable(new PicoPage(1, 100), new PicoSortable('userName', 'asc', 'email', 'desc', 'phone', 'asc'));
 ?>

Example 2: Using PicoLimit and PicoSortable

 <?php
 $pageable = new Pageable(new PicoLimit(0, 100), new PicoSortable('userName', 'asc', 'email', 'desc', 'phone', 'asc'));
 ?>

Example 3: Using an array for page and PicoSortable

 <?php
 $pageable = new Pageable([1, 100], new PicoSortable('userName', 'asc', 'email', 'desc', 'phone', 'asc'));
 ?>

Example 4: Using an array for both page and sortable

 <?php
 $pageable = new Pageable([1, 100], ['userName', 'asc', 'email', 'desc', 'phone', 'asc']);
 ?>

Example 5: Using PicoPage and an array for sortable

 <?php
 $pageable = new Pageable(new PicoPage(1, 100), ['userName', 'asc', 'email', 'desc', 'phone', 'asc']);
 ?>

Parameters

$page

The page or limit configuration. Can be:

$sortable

The sorting configuration. Can be:

2. getSortable

Declaration

public function getSortable() : PicoSortable|null
{
}

Description

Retrieves the sortable information.

Return

PicoSortable|null
3. setSortable

Declaration

public function setSortable(
    PicoSortable $sortable
) : self
{
}

Description

Sets the sortable information.

Parameters

$sortable

Sortable information.

Return

self

Returns the current instance for method chaining.

4. addSortable

Declaration

public function addSortable(
    string $sortBy,
    string $sortType
) : self
{
}

Description

Adds a sortable criterion.

Parameters

$sortBy

The field to sort by.

$sortType

The type of sorting (e.g., 'asc' or 'desc').

Return

self

Returns the current instance for method chaining.

Throws

InvalidParameterException

If $sortBy is null or empty.

5. createOrderBy

Declaration

public function createOrderBy(
    PicoTableInfo $tableInfo
) : string|null
{
}

Description

Creates the ORDER BY clause based on the current sortable criteria.

Parameters

$tableInfo

Information about the table.

Return

string|null

The ORDER BY clause or null if no sortable criteria exist.

6. getPage

Declaration

public function getPage() : PicoPage|null
{
}

Description

Retrieves the current page information.

Return

PicoPage|null
7. setPage

Declaration

public function setPage(
    PicoPage $page
) : self
{
}

Description

Sets the current page information.

Parameters

$page

Page information.

Return

self

Returns the current instance for method chaining.

8. getOffsetLimit

Declaration

public function getOffsetLimit() : PicoLimit|null
{
}

Description

Retrieves the offset and limit for database queries.

Return

PicoLimit|null
9. setOffsetLimit

Declaration

public function setOffsetLimit(
    PicoLimit $offsetLimit
) : self
{
}

Description

Sets the offset and limit for database queries.

Parameters

$offsetLimit

Offset and limit information.

Return

self

Returns the current instance for method chaining.

10. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

MagicObject\Database\PicoPageControl

Declaration

class PicoPageControl { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoPageControl

This class manages pagination controls for displaying pages of data. It generates navigation elements such as previous, next, first, and last page buttons, allowing users to navigate through pages seamlessly. The pagination links are generated based on the provided page data and can be customized with parameter names and paths.

Properties

1. pageData

Declaration

private PicoPageData $pageData;

Description

Page data object containing pagination information.

2. parameterName

Declaration

private string $parameterName;

Description

Parameter name used for pagination in the URL.

3. path

Declaration

private string $path;

Description

Base path for pagination links.

4. prev

Declaration

private string $prev;

Description

Symbol for the previous page button.

5. next

Declaration

private string $next;

Description

Symbol for the next page button.

6. first

Declaration

private string $first;

Description

Symbol for the first page button.

7. last

Declaration

private string $last;

Description

Symbol for the last page button.

8. formatPageNumber

Declaration

private string $formatPageNumber = '<span class="page-selector page-selector-number%s" data-page-number="%d"><a href="%s">%s</a></span>';

Description

Template for rendering a specific page number in pagination.

9. formatStepOne

Declaration

private string $formatStepOne = '<span class="page-selector page-selector-step-one%s" data-page-number="%d"><a href="%s">%s</a></span>';

Description

Template for rendering navigation buttons like "next" or "prev" in pagination.

10. formatStartEnd

Declaration

private string $formatStartEnd = '<span class="page-selector page-selector-end%s" data-page-number="%d"><a href="%s">%s</a></span>';

Description

Template for rendering navigation buttons like "first" or "last" in pagination.

Methods

1. __construct

Declaration

public function __construct(
    PicoPageData $pageData,
    string $parameterName = 'page',
    string|null $path = null
)
{
}

Description

Constructor for the PicoPageControl class.

Initializes pagination control with page data and optional parameter name and path.

Parameters

$pageData

Page data object for pagination.

$parameterName

Parameter name for the page (default is 'page').

$path

Full path for generating pagination links (optional).

2. isNotEmpty

Declaration

private function isNotEmpty(
    mixed $value
) : bool
{
}

Description

Checks if a value is set and not empty.

Parameters

$value

The value to check.

Return

bool

Returns true if the value is set and not empty, otherwise false.

3. setNavigation

Declaration

public function setNavigation(
    string|null $prev = null,
    string|null $next = null,
    string|null $first = null,
    string|null $last = null
) : self
{
}

Description

Sets custom navigation symbols for pagination buttons.

This method allows you to define custom symbols for navigation buttons, including the previous, next, first, and last page buttons. Only non-null values will be assigned to their respective properties.

Parameters

$prev

The symbol to display for the "previous" page button (optional).

$next

The symbol to display for the "next" page button (optional).

$first

The symbol to display for the "first" page button (optional).

$last

The symbol to display for the "last" page button (optional).

Return

self

Returns the current instance for method chaining.

4. setMargin

Declaration

public function setMargin(
    int $margin
) : self
{
}

Description

Sets the margin for pagination controls.

This defines how many pages to show before and after the current page.

Parameters

$margin

Margin (number of pages before and after the current page).

Return

self

Returns the current instance for method chaining.

5. setRange

Declaration

public function setRange(
    int $range
) : self
{
}

Description

Sets the range for pagination controls.

This defines how many pages to show before and after the current page.

Parameters

$range

Range (number of pages before and after the current page).

Return

self

Returns the current instance for method chaining.

6. setPageRange

Declaration

public function setPageRange(
    int $range
) : self
{
}

Description

Sets the page range for pagination controls.

This defines how many pages to show before and after the current page.

Parameters

$range

Range (number of pages before and after the current page).

Return

self

Returns the current instance for method chaining.

7. getFormatPageNumber

Declaration

public function getFormatPageNumber() : string
{
}

Description

Gets the template for rendering specific page numbers.

Return

string

The current format for rendering page numbers.

8. setFormatPageNumber

Declaration

public function setFormatPageNumber(
    string $formatPageNumber
) : self
{
}

Description

Sets the template for rendering specific page numbers.

This format is used to generate the HTML for individual page numbers in the pagination. It includes a span with the page-selector-number class and a link (<a>) to the page.

Placeholders:

  • %s: Additional CSS classes, e.g., page-selected.
  • %d: Page number for the data-page-number attribute.
  • %s: URL for the link (href attribute).
  • %s: Text content of the link (usually the page number).

    Example:

    <span class="page-selector page-selector-number%s" data-page-number="%d"><a href="%s">%s</a></span>

    will be

    <span class="page-selector page-selector-number page-selected" data-page-number="3">
    <a href="/path?page=3">3</a>
    </span>

Parameters

$formatPageNumber

The new format for rendering page numbers.

Return

self

Returns the current instance for method chaining.

9. getFormatStepOne

Declaration

public function getFormatStepOne() : string
{
}

Description

Gets the template for rendering step navigation buttons.

Return

string

The current format for step navigation buttons.

10. setFormatStepOne

Declaration

public function setFormatStepOne(
    string $formatStepOne
) : self
{
}

Description

Sets the template for rendering step navigation buttons.

This format generates the HTML for step navigation buttons, such as "previous" or "next." It includes a span with the page-selector-step-one class and a link (<a>) to the target page.

Placeholders:

  • %s: Additional CSS classes (e.g., active state).
  • %d: Page number for the data-page-number attribute.
  • %s: URL for the link (href attribute).
  • %s: Symbol or text for the button (e.g., "Next" or "Prev").

    Example:

    <span class="page-selector page-selector-step-one%s" data-page-number="%d"><a href="%s">%s</a></span>

    will be

    <span class="page-selector page-selector-step-one" data-page-number="4">
    <a href="/path?page=4">Next</a>
    </span>

Parameters

$formatStepOne

The new format for step navigation buttons.

Return

self

Returns the current instance for method chaining.

11. getFormatStartEnd

Declaration

public function getFormatStartEnd() : string
{
}

Description

Gets the template for rendering end navigation buttons.

Return

string

The current format for end navigation buttons.

12. setFormatStartEnd

Declaration

public function setFormatStartEnd(
    string $formatStartEnd
) : self
{
}

Description

Sets the template for rendering end navigation buttons.

This format generates the HTML for step navigation buttons, such as "previous" or "next." It includes a span with the page-selector-step-one class and a link (<a>) to the target page.

Placeholders:

  • %s: Additional CSS classes (e.g., active state).
  • %d: Page number for the data-page-number attribute.
  • %s: URL for the link (href attribute).
  • %s: Symbol or text for the button (e.g., "Start" or "End").

    Example:

    <span class="page-selector page-selector-end%s" data-page-number="%d"><a href="%s">%s</a></span>

    will be

    <span class="page-selector page-selector-end" data-page-number="4">
    <a href="/path?page=4">End</a>
    </span>

Parameters

$formatStartEnd

The new format for end navigation buttons.

Return

self

Returns the current instance for method chaining.

13. setButtonFormat

Declaration

public function setButtonFormat(
    string $pageNumberFormat,
    string $stepOneFormat,
    string $startEndFormat
) : self
{
}

Description

Sets the button format templates for pagination controls.

This method allows you to set custom templates for page numbers, step buttons and start/end buttons.

Parameters

$pageNumberFormat

The format template for rendering page numbers.

$stepOneFormat

The format template for rendering step buttons.

$startEndFormat

The format template for rendering start and end buttons.

Return

self

Returns the current instance for method chaining.

14. setPaginationConfig

Declaration

public function setPaginationConfig(
    SecretObject $paginationConfig
) : self
{
}

Description

Applies the pagination configuration to the current instance.

This method accepts a configuration object, typically sourced from a Yaml file, and applies its settings to the pagination control. The object contains the following properties:

Parameters

$paginationConfig

The configuration object containing pagination settings.

Return

self

Returns the current instance for method chaining.

15. toHTML

Declaration

public function toHTML() : string
{
}

Description

Converts the pagination control to HTML format.

Return

string

HTML representation of the pagination controls.

16. __toString

Declaration

public function __toString() : string
{
}

Description

Generates the HTML for pagination controls.

Return

string

HTML representation of the pagination controls.

MagicObject\Database\PicoPageData

Declaration

class PicoPageData { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing paginated data for database queries.

The PicoPageData class encapsulates the results of a database query along with pagination details, execution timing, and other metadata. It provides methods to manage and retrieve paginated results effectively, allowing for easy integration into applications that require data manipulation and display.

Key Features

  • Encapsulates query results in a paginated format.
  • Supports execution time tracking for performance monitoring.
  • Provides easy access to pagination controls and metadata.
  • Facilitates fetching and processing of data with subquery mapping.

Constants

const RESULT = "result";
const PAGEABLE = "pageable";

Properties

1. result

Declaration

private MagicObject[] $result = array();

Description

Result data from the query.

2. pageable

Declaration

private PicoPageable $pageable;

Description

Pageable object that defines pagination settings.

3. totalResult

Declaration

private int $totalResult = 0;

Description

Total number of matching results from the query.

4. totalPage

Declaration

private int $totalPage = 0;

Description

Total number of pages based on pagination settings.

5. pageNumber

Declaration

private int $pageNumber = 1;

Description

Current page number in the pagination context.

6. pageSize

Declaration

private int $pageSize = 0;

Description

Number of results per page.

7. dataOffset

Declaration

private int $dataOffset = 0;

Description

Offset for retrieving data in the current pagination context.

8. startTime

Declaration

private float $startTime = 0.0;

Description

Start time of the query execution.

9. endTime

Declaration

private float $endTime = 0.0;

Description

End time of the query execution.

10. executionTime

Declaration

private float $executionTime = 0.0;

Description

Total execution time for the query in seconds.

11. pagination

Declaration

private array $pagination = array();

Description

Array holding pagination details for display.

12. stmt

Declaration

private PDOStatement $stmt;

Description

PDO statement associated with the query execution.

13. className

Declaration

private string $className;

Description

Class name of the entity being managed.

14. subqueryMap

Declaration

private array $subqueryMap;

Description

Mapping information for subqueries.

15. byCountResult

Declaration

private bool $byCountResult = false;

Description

Flag indicating whether the result was derived from a count query.

16. entity

Declaration

private MagicObject $entity;

Description

Entity associated with the results.

17. findOption

Declaration

private int $findOption = 0;

Description

Flags for controlling find options in the query.

Methods

1. __construct

Declaration

public function __construct(
    MagicObject[]|null $result = null,
    float $startTime = null,
    int $totalResult = 0,
    PicoPageable|null $pageable = null,
    PDOStatement|null $stmt = null,
    MagicObject|null $entity = null,
    array|null $subqueryMap = null
)
{
}

Description

Constructor for the PicoPageData class.

Initializes a new instance of the class with the specified parameters.

Parameters

$result

Array of MagicObject instances or null.

$startTime

Timestamp when the query was initiated.

$totalResult

Total count of results, defaults to 0.

$pageable

Pageable object for pagination settings.

$stmt

PDO statement associated with the query.

$entity

Entity associated with the query results.

$subqueryMap

Mapping for subquery results.

2. countData

Declaration

private function countData(
    array $result
) : int
{
}

Description

Count the number of items in the result set.

Parameters

$result

Result set to count.

Return

int

Count of items in the result.

3. calculateContent

Declaration

public function calculateContent() : self
{
}

Description

Calculate pagination content based on the pageable settings.

Return

self

Returns the current instance for method chaining.

4. initializeDefaultPagination

Declaration

private function initializeDefaultPagination(
    int $countResult
)
{
}

Description

Initialize default pagination settings.

This method is called when no pageable object is provided.

Parameters

$countResult

Total count of results.

5. generatePagination

Declaration

public function generatePagination(
    int $pageRange = 3
) : self
{
}

Description

Generate pagination details for display.

This method constructs an array of pagination controls based on the current page number and total pages.

Parameters

$pageRange

Number of pages to show before and after the current page.

Return

self

Returns the current instance for method chaining.

6. getResult

Declaration

public function getResult() : MagicObject[]
{
}

Description

Get result data from the query.

Return

MagicObject[]

Array of MagicObject instances.

7. getPageNumber

Declaration

public function getPageNumber() : int
{
}

Description

Get the current page number in the pagination context.

Return

int

Current page number.

8. getTotalPage

Declaration

public function getTotalPage() : int
{
}

Description

Get the total number of pages based on pagination settings.

Return

int

Total page count.

9. getPageSize

Declaration

public function getPageSize() : int
{
}

Description

Get the size of each page (number of results per page).

Return

int

Page size.

10. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

11. getExecutionTime

Declaration

public function getExecutionTime() : float
{
}

Description

Get the execution time of the query in seconds.

Return

float

Execution time.

12. getPagination

Declaration

public function getPagination() : array
{
}

Description

Get the pagination details for the current query.

Return

array

Pagination details.

13. getPageControl

Declaration

public function getPageControl(
    string $parameterName = 'page',
    string|null $path = null
) : PicoPageControl
{
}

Description

Get the pagination control object for managing page navigation.

Parameters

$parameterName

Parameter name for the page.

$path

Optional link path.

Return

PicoPageControl

Pagination control object.

14. getTotalResult

Declaration

public function getTotalResult() : int
{
}

Description

Get the total result count from the query.

Return

int

Total result count.

15. getPageable

Declaration

public function getPageable() : PicoPageable|null
{
}

Description

Get the pageable object associated with this data.

Return

PicoPageable|null

Pageable object or null if not set.

16. getDataOffset

Declaration

public function getDataOffset() : int
{
}

Description

Get the data offset for the current pagination context.

Return

int

Data offset.

17. getPDOStatement

Declaration

public function getPDOStatement() : PDOStatement
{
}

Description

Get the PDO statement associated with the query.

Return

PDOStatement

Throws

FindOptionException

if the statement is null.

18. fetch

Declaration

public function fetch() : MagicObject|mixed
{
}

Description

Fetch the next row from the result set.

Return

MagicObject|mixed

Next row data as a MagicObject or false on failure.

Throws

FindOptionException

if the statement is null.

19. applySubqueryResult

Declaration

public function applySubqueryResult(
    array $row
) : MagicObject
{
}

Description

Apply subquery results to the row data.

This method processes the row data and integrates results from subqueries as defined by the mapping.

Parameters

$row

Data row from the query result.

Return

MagicObject

Processed MagicObject instance containing the merged data.

20. getFindOption

Declaration

public function getFindOption() : int
{
}

Description

Get find option flags indicating query behavior.

Return

int

Find option flags.

21. setFindOption

Declaration

public function setFindOption(
    int $findOption
) : self
{
}

Description

Set find option flags to control query behavior.

Parameters

$findOption

Flags indicating the desired query options.

Return

self

Returns the current instance for method chaining.

MagicObject\Database\PicoPredicate

Declaration

class PicoPredicate { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoPredicate

A predicate for building query conditions in database queries. This class allows you to define various query conditions (e.g., equality, inequality, inclusion, pattern matching, etc.) to be used when constructing database queries.

Properties

Methods

1. __construct

Declaration

public function __construct(
    string|null $field = null,
    mixed|null $value = null
)
{
}

Description

Constructor. Initializes the predicate with a field and value.

If a field is provided, it sets the equality condition or an IN condition based on the value type.

Parameters

$field

The name of the field.

$value

The value to compare against.

2. isRequireJoin

Declaration

public function isRequireJoin() : bool
{
}

Description

Check if a real join table is required.

Return

bool

True if a join is required, false otherwise.

3. equals

Declaration

public function equals(
    string $field,
    mixed $value
) : self
{
}

Description

Set an equality condition.

Parameters

$field

The name of the field.

$value

The value to compare against.

Return

self

Returns the current instance for method chaining.

4. notEquals

Declaration

public function notEquals(
    string $field,
    mixed $value
) : self
{
}

Description

Set a not-equal condition.

Parameters

$field

The name of the field.

$value

The value to compare against.

Return

self

Returns the current instance for method chaining.

5. isNull

Declaration

public function isNull(
    string $field
) : self
{
}

Description

Set a condition for NULL.

Parameters

$field

The name of the field.

Return

self

Returns the current instance for method chaining.

6. isNotNull

Declaration

public function isNotNull(
    string $field
) : self
{
}

Description

Set a condition for NOT NULL.

Parameters

$field

The name of the field.

Return

self

Returns the current instance for method chaining.

7. in

Declaration

public function in(
    string $field,
    array $values
) : self
{
}

Description

Set an IN condition.

Parameters

$field

The name of the field.

$values

The values to include.

Return

self

Returns the current instance for method chaining.

8. inRange

Declaration

public function inRange(
    string $field,
    array $values
) : self
{
}

Description

Sets an IN RANGE condition.

Parameters

$field

The name of the field to compare.

$values

An array containing the lower and upper boundaries of the range.

Return

self

Returns the current instance for method chaining.

9. between

Declaration

public function between(
    string $field,
    mixed $min,
    mixed $max
) : self
{
}

Description

Sets a BETWEEN condition.

Parameters

$field

The name of the field to compare.

$min

The lower boundary of the range.

$max

The upper boundary of the range.

Return

self

Returns the current instance for method chaining.

10. notIn

Declaration

public function notIn(
    string $field,
    array $values
) : self
{
}

Description

Set a NOT IN condition.

Parameters

$field

The name of the field.

$values

The values to exclude.

Return

self

Returns the current instance for method chaining.

11. like

Declaration

public function like(
    string $field,
    mixed $value
) : self
{
}

Description

Set a LIKE condition.

Parameters

$field

The name of the field.

$value

The value to compare against.

Return

self

Returns the current instance for method chaining.

12. notLike

Declaration

public function notLike(
    string $field,
    mixed $value
) : self
{
}

Description

Set a NOT LIKE condition.

Parameters

$field

The name of the field.

$value

The value to compare against.

Return

self

Returns the current instance for method chaining.

13. lessThan

Declaration

public function lessThan(
    string $field,
    mixed $value
) : self
{
}

Description

Set a LESS THAN condition.

Parameters

$field

The name of the field.

$value

The value to compare against.

Return

self

Returns the current instance for method chaining.

14. greaterThan

Declaration

public function greaterThan(
    string $field,
    mixed $value
) : self
{
}

Description

Set a GREATER THAN condition.

Parameters

$field

The name of the field.

$value

The value to compare against.

Return

self

Returns the current instance for method chaining.

15. lessThanOrEquals

Declaration

public function lessThanOrEquals(
    string $field,
    mixed $value
) : self
{
}

Description

Set a LESS THAN OR EQUALS condition.

Parameters

$field

The name of the field.

$value

The value to compare against.

Return

self

Returns the current instance for method chaining.

16. greaterThanOrEquals

Declaration

public function greaterThanOrEquals(
    string $field,
    mixed $value
) : self
{
}

Description

Set a GREATER THAN OR EQUALS condition.

Parameters

$field

The name of the field.

$value

The value to compare against.

Return

self

Returns the current instance for method chaining.

17. getField

Declaration

public function getField() : string
{
}

Description

Get the field name.

Return

string

The name of the field.

18. getValue

Declaration

public function getValue() : mixed
{
}

Description

Get the value.

Return

mixed

The value being compared against.

19. getComparation

Declaration

public function getComparation() : PicoDataComparation|null
{
}

Description

Get the comparation instance.

Return

PicoDataComparation|null

The comparation instance or null.

20. getFilterLogic

Declaration

public function getFilterLogic() : string|null
{
}

Description

Get the filter logic.

Return

string|null

The filter logic or null.

21. setFilterLogic

Declaration

public function setFilterLogic(
    string $filterLogic
) : self
{
}

Description

Set the filter logic.

Parameters

$filterLogic

The filter logic to set.

Return

self

Returns the current instance for method chaining.

22. generateLikeStarts

Declaration

public static function generateLikeStarts(
    string $value
) : string
{
}

Description

Generate a LIKE clause that matches the start of a string.

Parameters

$value

The value to use for matching.

Return

string

The LIKE clause for matching the start.

23. generateLikeEnds

Declaration

public static function generateLikeEnds(
    string $value
) : string
{
}

Description

Generate a LIKE clause that matches the end of a string.

Parameters

$value

The value to use for matching.

Return

string

The LIKE clause for matching the end.

24. generateLikeContains

Declaration

public static function generateLikeContains(
    string $value
) : string
{
}

Description

Generate a LIKE clause that matches anywhere in a string.

Parameters

$value

The value to use for matching.

Return

string

The LIKE clause for matching anywhere.

25. __call

Declaration

public function __call(
    string $method,
    array $params
) : mixed
{
}

Description

Magic method to handle dynamic method calls for setting values.

This method intercepts calls to methods that are not explicitly defined in the class. It specifically looks for methods that start with "set" and performs an equality check between the property corresponding to the method and the provided value.

Supported dynamic method:

  • set<PropertyName>(value): Checks if the property value equals the provided value.

    • For example, calling $obj->setFoo($value) checks if the property foo is equal to $value using the equals method.

    If the method name does not start with "set" or if no value is provided, the method returns null.

Parameters

$method

The method name being called, expected to start with "set".

$params

The parameters passed to the method, expected to contain the value.

Return

mixed

The result of the equality check (true or false) or null if the method call is not handled.

26. __set

Declaration

public function __set(
    string $name,
    mixed $value
)
{
}

Description

Magic method to handle dynamic property assignment.

This method allows for setting property values dynamically.

Parameters

$name

The property name.

$value

The value to set.

27. getInstance

Declaration

public static function getInstance() : self
{
}

Description

Get an instance of this class.

Return

self

A new instance of PicoPredicate.

28. functionLower

Declaration

public static function functionLower(
    string $value
) : string
{
}

Description

Generate a SQL LOWER function call.

Parameters

$value

The value to wrap in the LOWER function.

Return

string

The SQL LOWER function call.

29. functionUpper

Declaration

public static function functionUpper(
    string $value
) : string
{
}

Description

Generate a SQL UPPER function call.

Parameters

$value

The value to wrap in the UPPER function.

Return

string

The SQL UPPER function call.

30. functionAndValue

Declaration

public static function functionAndValue(
    string $function,
    string $value
) : string
{
}

Description

Generate a SQL function call with a value.

Parameters

$function

The SQL function name.

$value

The value to pass to the function.

Return

string

The formatted SQL function call.

31. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

MagicObject\Database\PicoSort

Declaration

class PicoSort { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoSort

A class for defining sorting criteria for database queries. This class allows you to specify the field to sort by and the direction of sorting (ascending or descending).

Constants

const ORDER_TYPE_ASC = "asc";
const ORDER_TYPE_DESC = "desc";
const SORT_BY = "sortBy";

Properties

1. sortBy

Declaration

private string $sortBy = '';

Description

The field to sort by.

2. sortType

Declaration

private string $sortType = '';

Description

The type of sorting (ascending or descending).

Methods

1. __construct

Declaration

public function __construct(
    string|null $sortBy = null,
    string|null $sortType = null
)
{
}

Description

Constructor to initialize sorting criteria.

Parameters

$sortBy

The field to sort by.

$sortType

The type of sorting (asc or desc).

2. getSortBy

Declaration

public function getSortBy() : string
{
}

Description

Get the field to sort by.

Return

string

The field to sort by.

3. setSortBy

Declaration

public function setSortBy(
    string $sortBy
) : self
{
}

Description

Set the field to sort by.

Parameters

$sortBy

The field to sort by.

Return

self

Returns the current instance for method chaining.

4. getSortType

Declaration

public function getSortType() : string
{
}

Description

Get the type of sorting.

Return

string

The type of sorting (asc or desc).

5. setSortType

Declaration

public function setSortType(
    string $sortType
) : self
{
}

Description

Set the type of sorting.

Parameters

$sortType

The type of sorting (asc or desc).

Return

self

Returns the current instance for method chaining.

6. __call

Declaration

public function __call(
    string $method,
    array $params
) : self|null
{
}

Description

Magic method for dynamic method calls related to sorting criteria.

This method enables the dynamic setting of sorting criteria by allowing the invocation of methods prefixed with "sortBy". When such a method is called, it extracts the sorting field from the method name and assigns a sorting type based on the provided parameters.

Supported dynamic method:

  • sortBy<FieldName>(sortType): Sets the field to sort by and the type of sorting.

    • For example, calling $obj->sortByName('asc') would:
      • Set the sorting field to name.
      • Set the sorting type to asc.

    If the method name does not start with "sortBy" or if no parameters are provided, the method returns null.

Parameters

$method

The name of the method being called, expected to start with "sortBy".

$params

The parameters passed to the method; expected to contain the sorting type.

Return

self|null

Returns the current instance for method chaining or null if the method call is not handled.

7. getInstance

Declaration

public static function getInstance() : self
{
}

Description

Get an instance of PicoSort.

Return

self

A new instance of PicoSort.

8. fixSortType

Declaration

public static function fixSortType(
    string $type
) : string
{
}

Description

Normalize the sort type to either ascending or descending.

Parameters

$type

The desired sort type (asc or desc).

Return

string

The normalized sort type (asc or desc).

9. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

MagicObject\Database\PicoSortable

Declaration

class PicoSortable { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing sortable criteria for database queries.

This class provides functionality to manage sorting criteria, allowing the specification of fields to sort by and their sort types.

Properties

1. sortable

Declaration

private PicoSort[] $sortable = array();

Description

Array of sortable criteria.

Methods

1. __construct

Declaration

public function __construct()
{
}

Description

Constructor to initialize sortable criteria based on provided arguments.

Example:

 <?php
 $sortable = new PicoSortable(); // Without initialization
 // or
 $sortable = new PicoSortable("rank", "ASC", "name", "ASC"); // With initialization
2. initSortable

Declaration

private function initSortable(
    int $argc,
    array $params
) : self
{
}

Description

Initialize sortable criteria.

Parameters

$argc

Number of arguments passed to the constructor.

$params

Parameters for sorting.

Return

self

Returns the current instance for method chaining.

3. add

Declaration

public function add(
    PicoSort|array $sort
) : self
{
}

Description

Add a sortable criterion.

Parameters

$sort

The sorting criterion to add.

Return

self

Returns the current instance for method chaining.

4. addSortable

Declaration

public function addSortable(
    PicoSort|array $sort
) : self
{
}

Description

Add a sortable criterion.

Parameters

$sort

The sorting criterion to add.

Return

self

Returns the current instance for method chaining.

5. createSortable

Declaration

public function createSortable(
    string $sortBy,
    string $sortType
) : PicoSort
{
}

Description

Create a sortable criterion.

Parameters

$sortBy

The field to sort by.

$sortType

The type of sorting (ASC or DESC).

Return

PicoSort
6. createOrderBy

Declaration

public function createOrderBy(
    PicoTableInfo|null $tableInfo = null
) : string|null
{
}

Description

Create an ORDER BY clause based on the sortable criteria.

Parameters

$tableInfo

Information about the table for mapping.

Return

string|null

The ORDER BY clause, or null if there are no sortable criteria.

7. createWithoutMapping

Declaration

private function createWithoutMapping() : string
{
}

Description

Create an ORDER BY clause without mapping to table columns.

Return

string

The ORDER BY clause.

8. createWithMapping

Declaration

private function createWithMapping(
    PicoTableInfo $tableInfo
) : string
{
}

Description

Create an ORDER BY clause with mapping based on table information.

Parameters

$tableInfo

Information about the table for mapping.

Return

string

The ORDER BY clause.

9. isEmpty

Declaration

public function isEmpty() : bool
{
}

Description

Check if there are no sortable criteria.

Return

bool

True if there are no sortable criteria, false otherwise.

10. getSortable

Declaration

public function getSortable() : PicoSort[]
{
}

Description

Get the array of sortable criteria.

Return

PicoSort[]

Array of sortable criteria.

11. getInstance

Declaration

public static function getInstance() : self
{
}

Description

Get an instance of PicoSortable.

Return

self

A new instance of PicoSortable.

12. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

13. fromUserInput

Declaration

public static function fromUserInput(
    PicoRequestBase $request,
    string[]|null $map = null,
    array|null $defaultSortable = null
) : self
{
}

Description

Create a PicoSortable instance from user input.

Parameters

$request

The request containing sorting information.

$map

Mapping of request parameters to sorting fields.

$defaultSortable

Default sorting criteria if no user input is provided.

Return

self

A new instance of PicoSortable with the specified criteria.

14. isArray

Declaration

public static function isArray(
    mixed $array
) : bool
{
}

Description

Check if the given input is an array.

Parameters

$array

The input to check.

Return

bool

True if the input is an array, false otherwise.

MagicObject\Database\PicoSpecification

Declaration

class PicoSpecification { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoSpecification

This class is responsible for building complex database query specifications, allowing for the combination of predicates using logical operators (AND, OR).

Constants

const LOGIC_AND = "and";
const LOGIC_OR = "or";

Properties

1. parentFilterLogic

Declaration

private string $parentFilterLogic;

Description

Parent filter logic (AND/OR) for nested specifications.

2. specifications

Declaration

private PicoPredicate[] $specifications = array();

Description

Array of PicoPredicate objects representing individual conditions.

3. requireJoin

Declaration

private bool $requireJoin = false;

Description

Indicates whether a real join table is required in the database query.

4. defaultLogic

Declaration

private string $defaultLogic = 'and';

Description

Default logic for combining predicates (AND/OR).

Methods

1. getInstance

Declaration

public static function getInstance() : PicoSpecification
{
}

Description

Gets an instance of PicoSpecification.

Return

PicoSpecification

A new instance of PicoSpecification.

2. getInstanceOf

Declaration

public static function getInstanceOf(
    string|null $field = null,
    mixed|null $value = null
) : self
{
}

Description

Creates and returns an instance of the class with an optional PicoPredicate condition.

This static method creates a new instance of the class and, if the provided parameters are set, adds a PicoPredicate condition using the given field and value.

Parameters

$field

The name of the field to be used in the predicate.

$value

The value to compare against the field in the predicate.

Return

self

A new instance of the class with the optionally added predicate.

3. isRequireJoin

Declaration

public function isRequireJoin() : bool
{
}

Description

Checks if a real join table is required based on the specifications.

Return

bool

True if a join is required, false otherwise.

4. add

Declaration

public function add(
    PicoSpecification|PicoPredicate|array $predicate
) : self
{
}

Description

Adds a specification with default AND logic.

Parameters

$predicate

The filter to be added.

Return

self

Returns the current instance for method chaining.

5. addAnd

Declaration

public function addAnd(
    PicoSpecification|PicoPredicate|array $predicate
) : self
{
}

Description

Adds an AND specification.

Parameters

$predicate

The filter to be added.

Return

self

Returns the current instance for method chaining.

6. addOr

Declaration

public function addOr(
    PicoSpecification|PicoPredicate|array $predicate
) : self
{
}

Description

Adds an OR specification.

Parameters

$predicate

The filter to be added.

Return

self

Returns the current instance for method chaining.

7. addFilter

Declaration

private function addFilter(
    PicoSpecification|PicoPredicate|array $predicate,
    string $logic
) : self
{
}

Description

Adds a filter specification.

Parameters

$predicate

The filter to be added.

$logic

The logical operator (AND/OR) to use with this filter.

Return

self

Returns the current instance for method chaining.

8. addFilterByArray

Declaration

private function addFilterByArray(
    array $predicate,
    string $logic
) : self
{
}

Description

Adds a filter specification from an array.

Parameters

$predicate

The filter data represented as an associative array.

$logic

The logical operator (AND/OR) to use with these filters.

Return

self

Returns the current instance for method chaining.

9. addSubFilter

Declaration

private function addSubFilter(
    PicoSpecification|array $predicate,
    string $logic
) : self
{
}

Description

Adds a subfilter specification.

Parameters

$predicate

The subfilter to be added.

$logic

The logical operator (AND/OR) to use with this subfilter.

Return

self

Returns the current instance for method chaining.

10. isEmpty

Declaration

public function isEmpty() : bool
{
}

Description

Checks if the specifications collection is empty.

Return

bool

True if there are no specifications, false otherwise.

11. isArray

Declaration

public static function isArray(
    mixed $array
) : bool
{
}

Description

Check if the given input is an array.

Parameters

$array

The input to check.

Return

bool

True if the input is an array, false otherwise.

12. isValueEmpty

Declaration

public static function isValueEmpty(
    mixed $value
) : bool
{
}

Description

Checks if the given value is considered empty.

Parameters

$value

The value to check.

Return

bool

True if the value is empty, false otherwise.

13. getSpecifications

Declaration

public function getSpecifications() : PicoPredicate[]
{
}

Description

Retrieves the array of specifications.

Return

PicoPredicate[]

The array of PicoPredicate objects.

14. getParentFilterLogic

Declaration

public function getParentFilterLogic() : string|null
{
}

Description

Gets the parent filter logic for this specification.

Return

string|null

The parent filter logic, or null if not set.

15. setParentFilterLogic

Declaration

public function setParentFilterLogic(
    string $parentFilterLogic
) : self
{
}

Description

Sets the parent filter logic for this specification.

Parameters

$parentFilterLogic

The logical operator (AND/OR) for this specification.

Return

self

Returns the current instance for method chaining.

16. getWhere

Declaration

private function getWhere(
    PicoSpecification[] $specifications
) : string[]
{
}

Description

Creates a WHERE clause based on the current specifications.

Parameters

$specifications

The specifications to create the WHERE clause from.

Return

string[]

An array of strings representing the WHERE clause conditions.

17. getColumnName

Declaration

private function getColumnName(
    string $field,
    string|null $parentField
) : string
{
}

Description

Retrieves the full column name, including any parent field.

This method returns the column name formatted as "parentField.field" if the parent field is provided; otherwise, it returns just the field name.

Parameters

$field

The field name of the entity.

$parentField

The parent field name, if applicable.

Return

string

The full column name, either just the field name or the parent field concatenated with the field.

18. createWhereFromSpecification

Declaration

private function createWhereFromSpecification(
    PicoSpecification $specification
) : string
{
}

Description

Creates a WHERE clause from the given specification.

Parameters

$specification

The filter specification to create the WHERE clause from.

Return

string

The constructed WHERE clause as a string.

19. hasValue

Declaration

private function hasValue(
    mixed $specification
) : bool
{
}

Description

Checks if the specification is not null and not empty.

Parameters

$specification

The specification to check.

Return

bool

True if the specification is valid, false otherwise.

20. __call

Declaration

public function __call(
    string $method,
    array $params
) : self|null
{
}

Description

Magic method to handle undefined method calls dynamically.

This method allows for dynamic handling of method calls that are not explicitly defined in the class. Specifically, it enables the setting of properties through methods prefixed with "set". When such a method is called, the method extracts the property name from the method name, and then it calls the addPredicate method to set the corresponding value.

Supported dynamic method:

  • set<FieldName>(value): Sets a predicate for the specified field. For example, calling $obj->setAge(30) would:

    • Extract the field name age from the method name.
    • Call addPredicate('age', 30) to set the value.

    If the method name does not start with "set" or if the parameters are not provided, the method returns null.

Parameters

$method

The name of the method being called, expected to start with "set".

$params

The parameters passed to the method; expected to contain the value to set.

Return

self|null

Returns the current instance for method chaining if the method is valid, or null otherwise.

21. __set

Declaration

public function __set(
    string $field,
    mixed|mixed[] $value
)
{
}

Description

Magic method to set values dynamically using property assignment.

Parameters

$field

The field name to set.

$value

The value(s) to set for the field.

22. addPredicate

Declaration

private function addPredicate(
    string $field,
    mixed|mixed[] $value
) : self
{
}

Description

Adds a predicate to the specifications based on the field and value.

Parameters

$field

The field name to which the value is assigned.

$value

The value(s) to set for the field.

Return

self

Returns the current instance for method chaining.

23. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

24. fromUserInput

Declaration

public static function fromUserInput(
    PicoRequestBase $request,
    PicoSpecificationFilter[]|null $map = null
) : PicoSpecification
{
}

Description

Gets a specification based on user input.

Parameters

$request

The request object containing user input.

$map

The filter map defining expected filters.

Return

PicoSpecification

The constructed specification based on user input.

25. fixInput

Declaration

private static function fixInput(
    mixed $filterValue,
    PicoSpecificationFilter $filter
) : mixed
{
}

Description

Adjusts the filter value based on the filter's configuration.

This method ensures that the input value aligns with the filter type. If the filter does not expect an array but the input is an array, the first value in the array is selected. If no adjustment is needed, the input value is returned as-is.

Parameters

$filterValue

The raw user input value.

$filter

The filter object specifying expected data type.

Return

mixed

The adjusted value, based on the filter's configuration.

26. fullTextSearch

Declaration

public static function fullTextSearch(
    string $columnName,
    string $keywords
) : self
{
}

Description

Creates a full text search specification based on keywords.

Parameters

$columnName

The column name to search within.

$keywords

The keywords to search for.

Return

self

A new specification containing the full text search predicates.

27. filter

Declaration

public static function filter(
    string $columnName,
    string $dataType
) : PicoSpecificationFilter
{
}

Description

Creates a filter object based on column name and data type.

Parameters

$columnName

The column name to filter by.

$dataType

The data type of the column (e.g., string, integer).

Return

PicoSpecificationFilter

A new instance of PicoSpecificationFilter.

28. getDefaultLogic

Declaration

public function getDefaultLogic() : string
{
}

Description

Gets the default logic used for combining predicates.

Return

string

The default logic (AND/OR).

29. setDefaultLogic

Declaration

public function setDefaultLogic(
    string $defaultLogic
) : self
{
}

Description

Sets the default logic used for combining predicates.

Parameters

$defaultLogic

The default logic (AND/OR) to set.

Return

self

Returns the current instance for method chaining.

30. setDefaultLogicAnd

Declaration

public function setDefaultLogicAnd() : self
{
}

Description

Sets the default logic to AND.

Return

self

Returns the current instance for method chaining.

31. setDefaultLogicOr

Declaration

public function setDefaultLogicOr() : self
{
}

Description

Sets the default logic to OR.

Return

self

Returns the current instance for method chaining.

32. getRequireJoin

Declaration

public function getRequireJoin() : bool
{
}

Description

Checks if a real join table is required based on the specifications.

Return

bool

True if a join is required, false otherwise.

MagicObject\Database\PicoSpecificationFilter

Declaration

class PicoSpecificationFilter { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a specification filter.

This class defines filters for columns, specifying the data type and providing methods to convert values based on the defined type.

Constants

const DATA_TYPE_NUMBER = "number";
const DATA_TYPE_STRING = "string";
const DATA_TYPE_BOOLEAN = "boolean";
const DATA_TYPE_ARRAY_NUMBER = "number[]";
const DATA_TYPE_ARRAY_STRING = "string[]";
const DATA_TYPE_ARRAY_BOOLEAN = "boolean[]";
const DATA_TYPE_FULLTEXT = "fulltext";

Properties

1. columnName

Declaration

private string $columnName;

Description

The name of the column this filter applies to.

2. dataType

Declaration

private string $dataType;

Description

The data type of the column (e.g., number, string, boolean).

Methods

1. __construct

Declaration

public function __construct(
    string $columnName,
    string $dataType
)
{
}

Description

Constructor for PicoSpecificationFilter.

Initializes the column name and data type.

Parameters

$columnName

The name of the column.

$dataType

The data type of the column.

2. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation for debugging.

This method is intended for debugging purposes only and provides a JSON representation of the object's state.

Return

string

The JSON representation of the object.

3. valueOf

Declaration

public function valueOf(
    mixed $stringValue
) : mixed
{
}

Description

Converts a given value to the appropriate type based on the filter's data type.

Parameters

$stringValue

The value to convert.

Return

mixed

The converted value, typecasted as needed.

4. isArray

Declaration

public function isArray() : bool
{
}

Description

Checks if the data type represents an array.

This method determines whether the data type contains an array-like structure based on the presence of square brackets ([]).

Return

bool

True if the data type represents an array, false otherwise.

5. getArrayNumber

Declaration

private function getArrayNumber(
    mixed $stringValue
) : float[]|int[]
{
}

Description

Converts a value to an array of numbers.

Parameters

$stringValue

The value to convert.

Return

float[]|int[]

An array of numeric values.

6. getArrayBoolean

Declaration

private function getArrayBoolean(
    mixed $stringValue
) : bool[]
{
}

Description

Converts a value to an array of booleans.

Parameters

$stringValue

The value to convert.

Return

bool[]

An array of boolean values.

7. getNumber

Declaration

private function getNumber(
    mixed $stringValue
) : float|int
{
}

Description

Converts a value to a number.

Parameters

$stringValue

The value to convert.

Return

float|int

The converted numeric value.

8. getBoolean

Declaration

private function getBoolean(
    mixed $stringValue
) : bool
{
}

Description

Converts a value to a boolean.

Parameters

$stringValue

The value to convert.

Return

bool

The converted boolean value.

9. isNumber

Declaration

public function isNumber() : bool
{
}

Description

Checks if the data type is a number.

Return

bool

True if the data type is a number, false otherwise.

10. isString

Declaration

public function isString() : bool
{
}

Description

Checks if the data type is a string.

Return

bool

True if the data type is a string, false otherwise.

11. isBoolean

Declaration

public function isBoolean() : bool
{
}

Description

Checks if the data type is a boolean.

Return

bool

True if the data type is a boolean, false otherwise.

12. isArrayNumber

Declaration

public function isArrayNumber() : bool
{
}

Description

Checks if the data type is an array of numbers.

Return

bool

True if the data type is an array of numbers, false otherwise.

13. isArrayString

Declaration

public function isArrayString() : bool
{
}

Description

Checks if the data type is an array of strings.

Return

bool

True if the data type is an array of strings, false otherwise.

14. isArrayBoolean

Declaration

public function isArrayBoolean() : bool
{
}

Description

Checks if the data type is an array of booleans.

Return

bool

True if the data type is an array of booleans, false otherwise.

15. isFulltext

Declaration

public function isFulltext() : bool
{
}

Description

Checks if the data type is full text.

Return

bool

True if the data type is full text, false otherwise.

16. getColumnName

Declaration

public function getColumnName() : string
{
}

Description

Gets the column name of this filter.

Return

string

The name of the column.

17. getDataType

Declaration

public function getDataType() : string
{
}

Description

Gets the data type of this filter.

Return

string

The data type of the column.

MagicObject\Database\PicoSqlite

Declaration

class PicoSqlite extends MagicObject\Database\PicoDatabase { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoSqlite

A simple wrapper for SQLite database operations using PDO.

This class provides an easy-to-use interface for interacting with an SQLite database. It supports basic CRUD (Create, Read, Update, Delete) operations such as creating tables, inserting records, selecting records with optional conditions, updating records, and deleting records.

The class uses PDO (PHP Data Objects) for database connectivity and supports executing SQL queries through various methods. The connection to the SQLite database is made through the provided file path, and additional callbacks can be provided for query execution and debugging.

This class extends the PicoDatabase class, which provides additional database interaction capabilities.

Constants

const LOGIC_AND = " and ";

Properties

1. databaseFilePath

Declaration

private string $databaseFilePath;

Description

Database file path

2. databaseCredentials

Declaration

protected SecretObject $databaseCredentials;

Description

Database credential.

3. connected

Declaration

protected bool $connected = false;

Description

Indicates whether the database is connected or not.

4. autocommit

Declaration

protected bool $autocommit = true;

Description

Autocommit setting.

5. databaseConnection

Declaration

protected PDO $databaseConnection;

Description

Database connection.

6. databaseType

Declaration

protected string $databaseType = '';

Description

Database type.

7. callbackExecuteQuery

Declaration

protected callable $callbackExecuteQuery;

Description

Callback function when executing queries that modify data.

8. callbackDebugQuery

Declaration

protected callable $callbackDebugQuery;

Description

Callback function when executing any query.

Methods

3. tableExists

Declaration

public function tableExists(
    string $tableName
) : bool
{
}

Description

Check if a table exists in the database.

Parameters

$tableName

The name of the table to check.

Return

bool

True if the table exists, false otherwise.

4. createTable

Declaration

public function createTable(
    string $tableName,
    string[] $columns
) : int|false
{
}

Description

Create a new table in the database.

Parameters

$tableName

The name of the table to create.

$columns

An array of columns in the format 'column_name TYPE'.

Return

int|false

Returns the number of rows affected or false on failure.

5. insert

Declaration

public function insert(
    string $tableName,
    array $data
) : bool
{
}

Description

Insert a new record into the specified table.

Parameters

$tableName

The name of the table to insert into.

$data

An associative array of column names and values to insert.

Return

bool

Returns true on success or false on failure.

6. select

Declaration

public function select(
    string $tableName,
    array $conditions = array ( )
) : array
{
}

Description

Select records from the specified table with optional conditions.

Parameters

$tableName

The name of the table to select from.

$conditions

An associative array of conditions for the WHERE clause.

Return

array

Returns an array of fetched records as associative arrays.

7. update

Declaration

public function update(
    string $tableName,
    array $data,
    array $conditions
) : bool
{
}

Description

Update existing records in the specified table based on conditions.

Parameters

$tableName

The name of the table to update.

$data

An associative array of column names and new values.

$conditions

An associative array of conditions for the WHERE clause.

Return

bool

Returns true on success or false on failure.

8. delete

Declaration

public function delete(
    string $tableName,
    array $conditions
) : bool
{
}

Description

Delete records from the specified table based on conditions.

Parameters

$tableName

The name of the table to delete from.

$conditions

An associative array of conditions for the WHERE clause.

Return

bool

Returns true on success or false on failure.

MagicObject\Database\PicoSqlJson

Declaration

class PicoSqlJson { }

Package

MagicObject\Database

Description

Class PicoSqlJson

This class handles the encoding and validation of JSON data. It accepts an object, array, or a valid JSON string and ensures that it is properly encoded as a JSON string. If a string is provided, it checks if the string is a valid JSON format before encoding it. If the string is not valid JSON, an exception will be thrown.

Properties

1. value

Declaration

private string $value;

Description

The JSON encoded value

Methods

1. __construct

Declaration

public function __construct(
    mixed $value = null
)
{
}

Description

Constructor for PicoSqlJson class

Accepts an array, object, or a valid JSON string, and encodes it to JSON. If a string is provided, it checks whether it's a valid JSON string. If valid, it is encoded to JSON; otherwise, an exception is thrown.

Parameters

$value

The value to encode. Can be an array, object, or JSON string.

Throws

InvalidArgumentException

If the string provided is not valid JSON.

2. __toString

Declaration

public function __toString() : string
{
}

Description

Converts the object to a string.

This method returns the JSON-encoded value of the object when the object is treated as a string (e.g., when echoing or concatenating the object).

Return

string

The JSON string representation of the object.

MagicObject\Database\PicoTableInfo

Declaration

class PicoTableInfo { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing information about a database table.

This class contains details such as the table name, columns, primary keys, and other related metadata necessary for managing database interactions.

Properties

1. tableName

Declaration

protected string $tableName;

Description

The name of the table.

2. columns

Declaration

protected array $columns = array();

Description

The columns of the table.

3. joinColumns

Declaration

protected array $joinColumns = array();

Description

The columns used for joining other tables.

4. primaryKeys

Declaration

protected array $primaryKeys = array();

Description

The primary keys of the table.

5. autoIncrementKeys

Declaration

protected array $autoIncrementKeys = array();

Description

The columns that auto-increment.

6. defaultValue

Declaration

protected array $defaultValue = array();

Description

The columns that have default values.

7. notNullColumns

Declaration

protected array $notNullColumns = array();

Description

The columns that cannot be null.

8. columnType

Declaration

protected string $columnType;

Description

The type of the columns.

9. noCache

Declaration

protected boolean $noCache = false;

Description

Flag to disable cache when any entities join with this entity

10. package

Declaration

protected string $package;

Description

The package name or namespace.

11. sortedColumnName

Declaration

private array List of sorted column names. $sortedColumnName = array();

Description

List of sorted column names.

This property stores an array of column names in their sorted order.

Methods

1. getInstance

Declaration

public static function getInstance() : self
{
}

Description

Gets an instance of PicoTableInfo.

Return

self

A new instance of PicoPredicate.

2. __construct

Declaration

public function __construct(
    string|null $tableName,
    array $columns,
    array $joinColumns,
    array $primaryKeys,
    array $autoIncrementKeys,
    array $defaultValue,
    array $notNullColumns,
    bool $noCache = false,
    string $package = null
)
{
}

Description

Constructor for PicoTableInfo.

Initializes the table information with the provided parameters.

Parameters

$tableName

The name of the table.

$columns

The columns of the table.

$joinColumns

The columns used for joins.

$primaryKeys

The primary keys of the table.

$autoIncrementKeys

The auto-increment keys of the table.

$defaultValue

The columns with default values.

$notNullColumns

The columns that cannot be null.

$noCache

Flag to disable cache when any entities join with this entity

$package

The package name or namespace of the class

3. __toString

Declaration

public function __toString() : string
{
}

Description

Magic method to return a JSON representation of the object.

Return

string

JSON encoded string of the object's properties.

4. getColumnsMap

Declaration

public function getColumnsMap() : string[]
{
}

Description

Gets a map of column properties.

Return

string[]

An associative array mapping property names to column names.

5. getJoinColumnsMap

Declaration

public function getJoinColumnsMap() : string[]
{
}

Description

Gets a map of join column properties.

Return

string[]

An associative array mapping property names to join column names.

6. getTableName

Declaration

public function getTableName() : string|null
{
}

Description

Gets the name of the table.

Return

string|null

The name of the table.

7. setTableName

Declaration

public function setTableName(
    string $tableName
) : self
{
}

Description

Sets the name of the table.

Parameters

$tableName

The name of the table.

Return

self

Returns the current instance for method chaining.

8. getColumns

Declaration

public function getColumns() : array
{
}

Description

Gets the columns of the table.

Return

array

The columns of the table.

9. setColumns

Declaration

public function setColumns(
    array $columns
) : self
{
}

Description

Sets the columns of the table.

Parameters

$columns

The columns to set.

Return

self

Returns the current instance for method chaining.

10. getJoinColumns

Declaration

public function getJoinColumns() : array
{
}

Description

Gets the join columns of the table.

Return

array

The join columns.

11. setJoinColumns

Declaration

public function setJoinColumns(
    array $joinColumns
) : self
{
}

Description

Sets the join columns of the table.

Parameters

$joinColumns

The join columns to set.

Return

self

Returns the current instance for method chaining.

12. getPrimaryKeys

Declaration

public function getPrimaryKeys() : array
{
}

Description

Gets the primary keys of the table.

Return

array

The primary keys.

13. setPrimaryKeys

Declaration

public function setPrimaryKeys(
    array $primaryKeys
) : self
{
}

Description

Sets the primary keys of the table.

Parameters

$primaryKeys

The primary keys to set.

Return

self

Returns the current instance for method chaining.

14. getAutoIncrementKeys

Declaration

public function getAutoIncrementKeys() : array
{
}

Description

Gets the auto-increment keys of the table.

Return

array

The auto-increment keys.

15. setAutoIncrementKeys

Declaration

public function setAutoIncrementKeys(
    array $autoIncrementKeys
) : self
{
}

Description

Sets the auto-increment keys of the table.

Parameters

$autoIncrementKeys

The auto-increment keys to set.

Return

self

Returns the current instance for method chaining.

16. getDefaultValue

Declaration

public function getDefaultValue() : array
{
}

Description

Gets the default value keys of the table.

Return

array

The default value keys.

17. setDefaultValue

Declaration

public function setDefaultValue(
    array $defaultValue
) : self
{
}

Description

Sets the default value keys of the table.

Parameters

$defaultValue

The default value keys to set.

Return

self

Returns the current instance for method chaining.

18. getNotNullColumns

Declaration

public function getNotNullColumns() : array
{
}

Description

Gets the not-null columns of the table.

Return

array

The not-null columns.

19. setNotNullColumns

Declaration

public function setNotNullColumns(
    array $notNullColumns
) : self
{
}

Description

Sets the not-null columns of the table.

Parameters

$notNullColumns

The not-null columns to set.

Return

self

Returns the current instance for method chaining.

20. getNoCache

Declaration

public function getNoCache() : boolean
{
}

Description

Get flag to disable cache when any entities join with this entity

Return

boolean
21. setNoCache

Declaration

public function setNoCache(
    boolean $noCache
) : self
{
}

Description

Set flag to disable cache when any entities join with this entity

Parameters

$noCache

Flag to disable cache when any entities join with this entity

Return

self
22. getPackage

Declaration

public function getPackage() : string
{
}

Description

Get the package name or namespace.

Return

string
23. setPackage

Declaration

public function setPackage(
    string $package
) : self
{
}

Description

Set the package name or namespace.

Parameters

$package

The package name or namespace.

Return

self
24. getSortedColumnName

Declaration

public function getSortedColumnName() : array
{
}

Description

Get the sorted column names.

This method retrieves the list of sorted column names.

Return

array

List of sorted column names.

25. setSortedColumnName

Declaration

public function setSortedColumnName(
    array $sortedColumnName
) : self
{
}

Description

Set the sorted column names.

This method sets the list of sorted column names.

Parameters

$sortedColumnName

List of sorted column names.

Return

self

Returns the current instance for method chaining.

MagicObject\Database\PicoTableInfoExtended

Declaration

class PicoTableInfoExtended extends MagicObject\Database\PicoTableInfo { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing extended information about a database table.

This class extends the functionality of PicoTableInfo by providing methods for managing unique columns, join columns, primary keys, auto-increment keys, default values, and not-null columns.

Constants

const NAME = "name";
const PREV_NAME = "prevColumnName";
const ELEMENT = "element";

Properties

1. tableName

Declaration

protected string $tableName;

Description

The name of the table.

2. columns

Declaration

protected array $columns = array();

Description

The columns of the table.

3. joinColumns

Declaration

protected array $joinColumns = array();

Description

The columns used for joining other tables.

4. primaryKeys

Declaration

protected array $primaryKeys = array();

Description

The primary keys of the table.

5. autoIncrementKeys

Declaration

protected array $autoIncrementKeys = array();

Description

The columns that auto-increment.

6. defaultValue

Declaration

protected array $defaultValue = array();

Description

The columns that have default values.

7. notNullColumns

Declaration

protected array $notNullColumns = array();

Description

The columns that cannot be null.

8. columnType

Declaration

protected string $columnType;

Description

The type of the columns.

9. noCache

Declaration

protected boolean $noCache = false;

Description

Flag to disable cache when any entities join with this entity

10. package

Declaration

protected string $package;

Description

The package name or namespace.

Methods

2. uniqueColumns

Declaration

public function uniqueColumns() : self
{
}

Description

Removes duplicate columns based on their names.

Return

self

Returns the current instance for method chaining.

3. uniqueJoinColumns

Declaration

public function uniqueJoinColumns() : self
{
}

Description

Removes duplicate join columns based on their names.

Return

self

Returns the current instance for method chaining.

4. uniquePrimaryKeys

Declaration

public function uniquePrimaryKeys() : self
{
}

Description

Removes duplicate primary keys based on their names.

Return

self

Returns the current instance for method chaining.

5. uniqueAutoIncrementKeys

Declaration

public function uniqueAutoIncrementKeys() : self
{
}

Description

Removes duplicate auto-increment keys based on their names.

Return

self

Returns the current instance for method chaining.

6. uniqueDefaultValue

Declaration

public function uniqueDefaultValue() : self
{
}

Description

Removes duplicate default value keys based on their names.

Return

self

Returns the current instance for method chaining.

7. uniqueNotNullColumns

Declaration

public function uniqueNotNullColumns() : self
{
}

Description

Removes duplicate not-null columns based on their names.

Return

self

Returns the current instance for method chaining.

8. mergeList

Declaration

private function mergeList(
    array $tmp,
    array $oldListCheck,
    array $newList
) : array
{
}

Description

Merges a new list of items into an existing temporary list.

Parameters

$tmp

The temporary list.

$oldListCheck

The old list to check against.

$newList

The new list to merge.

Return

array

The updated temporary list.

9. getOldListCheck

Declaration

private function getOldListCheck(
    array $oldList
) : array
{
}

Description

Retrieves the old list for checking against.

Parameters

$oldList

The old list to retrieve.

Return

array

An array of column names from the old list.

10. mergeColumns

Declaration

public function mergeColumns(
    array $newList
) : self
{
}

Description

Merges a new list of columns into the existing columns, ensuring uniqueness.

Parameters

$newList

The new list of columns to merge.

Return

self

Returns the current instance for method chaining.

11. mergeJoinColumns

Declaration

public function mergeJoinColumns(
    array $newList
) : self
{
}

Description

Merges a new list of join columns into the existing join columns, ensuring uniqueness.

Parameters

$newList

The new list of join columns to merge.

Return

self

Returns the current instance for method chaining.

12. mergePrimaryKeys

Declaration

public function mergePrimaryKeys(
    array $newList
) : self
{
}

Description

Merges a new list of primary keys into the existing primary keys, ensuring uniqueness.

Parameters

$newList

The new list of primary keys to merge.

Return

self

Returns the current instance for method chaining.

13. mergeAutoIncrementKeys

Declaration

public function mergeAutoIncrementKeys(
    array $newList
) : self
{
}

Description

Merges a new list of auto-increment keys into the existing auto-increment keys, ensuring uniqueness.

Parameters

$newList

The new list of auto-increment keys to merge.

Return

self

Returns the current instance for method chaining.

14. mergeDefaultValue

Declaration

public function mergeDefaultValue(
    array $newList
) : self
{
}

Description

Merges a new list of default value keys into the existing default value keys, ensuring uniqueness.

Parameters

$newList

The new list of default value keys to merge.

Return

self

Returns the current instance for method chaining.

15. mergeNotNullColumns

Declaration

public function mergeNotNullColumns(
    array $newList
) : self
{
}

Description

Merges a new list of not-null columns into the existing not-null columns, ensuring uniqueness.

Parameters

$newList

The new list of not-null columns to merge.

Return

self

Returns the current instance for method chaining.

MagicObject\DataLabel\PicoDataLabel

Declaration

class PicoDataLabel extends MagicObject\SetterGetter { }

Package

MagicObject\DataLabel

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a data label with annotations for properties and tables.

This class uses annotations to define properties and their metadata.

Constants

const ANNOTATION_PROPERTIES = "Properties";
const ANNOTATION_TABLE = "Table";
const KEY_NAME = "name";
const ANNOTATION_VAR = "var";

Properties

1. classParams

Declaration

private array $classParams = array();

Description

Parameters defined in the class annotations.

2. className

Declaration

private string $className = '';

Description

Name of the class.

Methods

3. getObjectInfo

Declaration

public function getObjectInfo() : stdClass
{
}

Description

Retrieves object information by parsing class and property annotations.

Return

stdClass

An object containing the table name, columns, default values, and not-null columns.

MagicObject\PicoDataLabel\PicoDataLabels

Declaration

class PicoDataLabels { }

Package

MagicObject\DataLabel

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a collection of data labels.

This class allows for the storage and management of multiple data labels.

Properties

1. data

Declaration

private PicoDataLabel[] $data = array();

Description

Collection of data labels.

Methods

1. append

Declaration

public function append(
    PicoDataLabel $data
) : self
{
}

Description

Appends a new data label to the collection.

Parameters

$data

The data label to be added.

Return

self

Returns the current instance for method chaining.

2. generate

Declaration

public function generate()
{
}

Description

Generates output based on the collected data labels.

This method processes each data label in the collection.

MagicObject\Exceptions\ClassNotFoundException

Declaration

class ClassNotFoundException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class ClassNotFoundException

Custom exception class for handling scenarios where a class could not be found. This exception is typically thrown when attempting to use or instantiate a class that does not exist or is not autoloaded properly. It can be used in situations such as when a class name is misspelled, or the class file is not found in the expected location.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\CurlException

Declaration

class CurlException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class CurlException

Custom exception class for handling errors related to cURL operations. This exception is typically thrown when there is an issue with a cURL request, such as network failure, timeouts, or invalid responses from the server.

The CurlException class allows you to capture and manage errors related to cURL requests, providing detailed information about the error message, code, and the previous exception if any. It extends the built-in Exception class, and can be caught and handled just like any other exception in PHP.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\EmptyResultException

Declaration

class EmptyResultException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class EmptyResultException

Custom exception class for handling scenarios where a result is expected but none is returned. This can be useful for database queries or API calls where a missing result should be treated as an exceptional case.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\EntityException

Declaration

class EntityException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class EntityException

Custom exception class for handling errors related to entity operations. This can include issues such as validation failures, database errors, or other exceptions that occur during entity processing.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\ErrorConnectionException

Declaration

class ErrorConnectionException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class ErrorConnectionException

Custom exception class for handling errors related to connection issues. This exception is typically thrown when a connection attempt to a remote service, database, or external resource fails. It can be used in scenarios where the system expects a successful connection but encounters issues, such as timeouts, server unavailability, or invalid credentials.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\FileNotFoundException

Declaration

class FileNotFoundException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class FileNotFoundException

Custom exception class for handling file not found errors. This can be used in scenarios where a required file is missing, such as when attempting to read or access a file that does not exist.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\FindOptionException

Declaration

class FindOptionException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class FindOptionException

Custom exception class for handling errors that occur during the process of finding or retrieving options. This exception can be thrown when an expected option is not found, whether in configuration settings, database queries, or other operational contexts.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidAddressException

Declaration

class InvalidAddressException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidAddressException

Custom exception class for handling errors related to invalid addresses. This exception can be thrown when an address fails validation or is found to be improperly formatted. It can be used in scenarios such as address processing in applications that require user input for locations, shipping, or billing addresses.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidAnnotationException

Declaration

class InvalidAnnotationException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidAnnotationException

Custom exception class for handling errors related to invalid annotations. This exception can be thrown when an annotation is improperly formatted, missing, or fails validation in contexts such as reflection, metadata processing, or any system relying on annotations for configuration.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidClassException

Declaration

class InvalidClassException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidClassException

Custom exception class for handling errors related to invalid class definitions. This exception can be thrown when a class cannot be instantiated or when a class is found to be improperly defined, potentially during reflection or dynamic class loading operations.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidDatabaseConfiguration

Declaration

class InvalidDatabaseConfiguration extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidDatabaseConfiguration

Custom exception class for handling errors related to invalid database configurations. This exception can be thrown when there are issues with database connection settings, such as incorrect credentials, missing parameters, or invalid configuration values.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidFileFormatException

Declaration

class InvalidFileFormatException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidFileFormatException

Custom exception class for handling errors related to invalid file formats. This exception can be thrown when a file fails validation based on expected format criteria, such as incorrect file extensions, corrupted files, or improper file structures. It is useful in file upload processes or data import functionalities.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidFilterException

Declaration

class InvalidFilterException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidFilterException

Custom exception class for handling errors related to invalid filters. This exception can be thrown when a filter is improperly defined, fails validation, or cannot be applied in contexts such as data querying, processing, or any operation relying on filters to refine results.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidInputFormatException

Declaration

class InvalidInputFormatException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidInputFormatException

Custom exception class for handling errors related to invalid input formats. This exception can be thrown when input data fails validation, is improperly structured, or does not meet expected format criteria. It is useful in scenarios such as form submissions, data processing, or API requests where specific input formats are required.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidParameterException

Declaration

class InvalidParameterException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidParameterException

Custom exception class for handling errors related to invalid parameters. This exception can be thrown when a function or method receives parameters that do not meet the expected criteria, such as invalid types, missing required values, or parameters that fall outside of acceptable ranges.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidPolygonException

Declaration

class InvalidPolygonException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidPolygonException

Custom exception class for handling errors related to invalid polygon definitions. This exception can be thrown when a polygon fails validation criteria, such as having an insufficient number of vertices, improper angle measurements, or invalid geometric configurations. It is useful in applications involving geometric computations, shape processing, or graphical representations.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidQueryInputException

Declaration

class InvalidQueryInputException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidQueryInputException

Thrown when there is an error with the format of annotation attributes applied to a class, property, or method.

This exception is triggered when annotations provided in the code do not meet the expected format or structure. Common scenarios for throwing this exception include:

  • Malformed annotation values.
  • Missing required parameters in annotations.
  • Incorrect application of annotations to classes, properties, or methods that do not support them.

    Example scenarios where this exception may be used:

  • A class is annotated with an unsupported attribute or a malformed annotation.
  • A property is annotated with an incorrect attribute that does not conform to the expected format.
  • A method receives an unsupported or malformed annotation, resulting in a failure during runtime or reflection processing.

    This exception is useful for catching annotation-related errors early in the code execution, allowing developers to quickly address any misconfigurations.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\InvalidReturnTypeException

Declaration

class InvalidReturnTypeException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class InvalidReturnTypeException

Exception thrown when a function or method returns a value that does not match the expected return type. This can occur in systems with strict typing or when there is a mismatch between a declared return type and the actual returned value during execution. It is particularly useful in frameworks or libraries that rely on reflection or type hinting to ensure correct return types.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Returns the previous exception if it exists, or null if there is no previous exception.

Return

Throwable|null

The previous exception

MagicObject\Exceptions\MandatoryTableNameException

Declaration

class MandatoryTableNameException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class MandatoryTableNameException

Custom exception class for handling errors related to missing mandatory table names in database operations. This exception can be thrown when an operation requires a table name but none is provided, leading to failures in query execution or data manipulation. It is particularly useful in database abstraction layers or ORM implementations.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NoColumnMatchException

Declaration

class NoColumnMatchException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NoColumnMatchException

Custom exception class for handling errors when no columns match during database operations. This exception can be thrown when a query fails to find any columns that satisfy the specified criteria, indicating that the expected data structure does not align with the available columns in the database. It is particularly useful in data mapping or ORM frameworks where column mappings are critical.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NoColumnUpdatedException

Declaration

class NoColumnUpdatedException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NoColumnUpdatedException

Custom exception class for handling errors when no columns have been updated during a database operation. This exception can be thrown when an update query executes successfully but does not modify any records, indicating that the specified criteria did not match any existing entries. It is particularly useful in scenarios where data integrity and confirmation of changes are critical.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NoDatabaseConnectionException

Declaration

class NoDatabaseConnectionException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NoDatabaseConnectionException

Custom exception class for handling errors related to the absence of a database connection. This exception can be thrown when an application attempts to execute a database operation but fails to establish a connection to the database, possibly due to misconfiguration, network issues, or the database server being down. It is essential for managing connection-related errors in database-driven applications.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NoInsertableColumnException

Declaration

class NoInsertableColumnException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NoInsertableColumnException

Custom exception class for handling errors when there are no columns available for insertion during a database operation. This exception can be thrown when an attempt is made to insert data into a database table but the specified columns are either not defined or not allowed for insertion, possibly due to misconfiguration or constraints on the database schema. It is essential for ensuring that data integrity is maintained during insert operations.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NoPrimaryKeyDefinedException

Declaration

class NoPrimaryKeyDefinedException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NoPrimaryKeyDefinedException

Custom exception class for handling errors when a database entity lacks a defined primary key. This exception can be thrown during operations that require a primary key for identifying records, such as updates or deletions. It is crucial for ensuring data integrity and consistency within database operations, especially in ORM frameworks where primary keys are essential for object mapping.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NoRecordFoundException

Declaration

class NoRecordFoundException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NoRecordFoundException

Custom exception class for handling scenarios where a database query does not return any records. This exception is useful in situations where a lookup operation fails to find the requested data, helping to differentiate between successful queries with no results and errors in the query itself. It can be particularly useful in data retrieval operations, ensuring that the calling code can handle the absence of records appropriately.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NotNullColumnException

Declaration

class NotNullColumnException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NotNullColumnException

Custom exception class for handling errors related to database operations where a column defined as NOT NULL is being assigned a null value. This exception can be thrown during insert or update operations, ensuring that the integrity of the database schema is maintained. It is essential for catching issues that may arise from improper data handling or validation before attempting to store records in the database.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NoUpdatableColumnException

Declaration

class NoUpdatableColumnException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NoUpdatableColumnException

Custom exception class for handling scenarios where an attempt is made to update a database record, but no columns are available for updating. This exception is typically thrown during operations where it is essential to have at least one updatable column defined, such as in ORM frameworks or data access layers. It helps to ensure that update operations are valid and that the integrity of the database is maintained.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\NullPointerException

Declaration

class NullPointerException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class NullPointerException

Custom exception class for handling null reference errors in the application. This exception is typically thrown when an operation is attempted on a variable that is null, indicating that the application is trying to access or modify an object or variable that has not been initialized. This exception helps in identifying issues related to null values, ensuring better debugging and error handling.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\UnknownErrorException

Declaration

class UnknownErrorException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class UnknownErrorException

Custom exception class for handling null reference errors in the application. This exception is typically thrown when an operation is attempted on a variable that is null, indicating that the application is trying to access or modify an object or variable that has not been initialized. This exception helps in identifying issues related to null values, ensuring better debugging and error handling.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\UnsupportedDatabaseException

Declaration

class UnsupportedDatabaseException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class UnsupportedDatabaseException

Custom exception class for handling null reference errors in the application. This exception is typically thrown when an operation is attempted on a variable that is null, indicating that the application is trying to access or modify an object or variable that has not been initialized. This exception helps in identifying issues related to null values, ensuring better debugging and error handling.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\Exceptions\YamlException

Declaration

class YamlException extends Exception implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class YamlException

Custom exception class for handling errors related to YAML parsing or processing. This class extends the base Exception class to provide additional context for YAML-specific errors and maintains a reference to a previous exception if available.

It is useful for scenarios where detailed error handling and chaining of exceptions are required during YAML processing.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception in the chain (if any).

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception in the chain.

Return

Throwable|null

The previous exception if available, or null.

MagicObject\Exceptions\ZeroArgumentException

Declaration

class ZeroArgumentException extends InvalidArgumentException implements Throwable { }

Package

MagicObject\Exceptions

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class ZeroArgumentException

Custom exception class for handling cases where a method or function is called with zero arguments when at least one is expected. This exception extends the built-in InvalidArgumentException to provide more specific error handling for invalid input scenarios. It can help in identifying issues related to argument validation in function calls, ensuring that methods are invoked correctly with the necessary parameters.

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

Methods

2. getPreviousException

Declaration

public function getPreviousException() : Throwable|null
{
}

Description

Get the previous exception.

Return

Throwable|null

MagicObject\File\PicoDownloadFile

Declaration

class PicoDownloadFile { }

Package

MagicObject\File

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDownloadFile

Facilitates downloading a file, with support for partial content (range requests). This class ensures that requested files exist, handles errors, and supports downloading large files efficiently by sending them in chunks.

Properties

1. filepath

Declaration

private $filepath;

Description

@var string The path to the file being downloaded.

2. filename

Declaration

private $filename;

Description

@var string The filename to be used in the download response.

Methods

1. __construct

Declaration

public function __construct(
    string $filepath,
    string|null $filename = null
)
{
}

Description

PicoDownloadFile constructor.

Parameters

$filepath

The full path to the file.

$filename

The name of the file for download (optional).

2. download

Declaration

public function download(
    bool $exit = false
) : bool
{
}

Description

Initiates the download of the file with support for partial content (range requests).

Handles the following:

  • Verifies the file exists at the specified path.
  • Supports byte range requests for resuming downloads.
  • Sends appropriate HTTP headers for file transfer.
  • Streams the file to the client in chunks (8 KB by default).

Parameters

$exit

Whether to terminate the script after sending the file. Default is false.

Return

bool

Returns true if the entire file was successfully sent, false if only part of the file was sent.

3. fileExists

Declaration

private function fileExists() : bool
{
}

Description

Checks if the file exists.

Return

bool

True if the file exists, false otherwise.

4. sendError

Declaration

private function sendError(
    int $statusCode,
    string $message,
    int|null $fileSize = null
)
{
}

Description

Sends an error response with the given status code and message.

Parameters

$statusCode

The HTTP status code.

$message

The error message.

$fileSize

The file size to include in the Content-Range header (optional).

5. getRange

Declaration

private function getRange(
    int $fileSize
) : array
{
}

Description

Determines the byte range from the HTTP_RANGE header.

Parameters

$fileSize

The size of the file.

Return

array

The start and end byte positions for the range.

6. isInvalidRange

Declaration

private function isInvalidRange(
    int $start,
    int $end,
    int $fileSize
) : bool
{
}

Description

Checks if the byte range is valid.

Parameters

$start

The start byte.

$end

The end byte.

$fileSize

The total size of the file.

Return

bool

True if the range is invalid.

7. sendHeaders

Declaration

private function sendHeaders(
    int $start,
    int $end,
    int $fileSize
)
{
}

Description

Sends the appropriate HTTP headers for the download.

Parameters

$start

The start byte.

$end

The end byte.

$fileSize

The total size of the file.

8. streamFile

Declaration

private function streamFile(
    resource $fp,
    int $start,
    int $end
)
{
}

Description

Streams the file to the client in chunks.

Parameters

$fp

The file pointer.

$start

The start byte.

$end

The end byte.

MagicObject\File\PicoUploadFile

Declaration

class PicoUploadFile { }

Package

MagicObject\File

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing an upload file tool.

This class is designed to handle uploaded files. All attributes in this class are read-only.

Properties

1. map

Declaration

private array $map = array();

Description

Mapping of uploaded file names to their keys.

2. values

Declaration

private PicoUploadFileContainer[] $values = array();

Description

Array of uploaded file containers.

Methods

1. __construct

Declaration

public function __construct()
{
}

Description

Constructor.

Initializes the mapping of uploaded file names and populates the values.

2. __call

Declaration

public function __call(
    string $method,
    array $arguments
) : mixed
{
}

Description

Magic method to handle dynamic getter calls.

This method enables the retrieval of property values through dynamically named getter methods. It specifically handles methods that start with the prefix "get". When a getter method is called, the method extracts the property name from the method name, converts it to camel case, and retrieves the corresponding value from an internal storage.

If the requested property exists, its value is returned. If it does not exist, an instance of PicoUploadFileContainer is returned as an empty container.

Supported dynamic getter:

  • get<FieldName>: Retrieves the value associated with the specified field. For example, calling $obj->getFile() would:
    • Extract the field name file from the method name.
    • Look up the camel-cased key in the internal storage.
    • Return the associated value or a new PicoUploadFileContainer if the value is not found.

Parameters

$method

The name of the method being called, expected to start with "get".

$arguments

The arguments passed to the method; typically unused in getter methods.

Return

mixed

The value of the requested property if it exists; otherwise, an instance of PicoUploadFileContainer.

3. get

Declaration

public function get(
    string $name
) : PicoUploadFileContainer
{
}

Description

Get an uploaded file by parameter name.

Parameters

$name

The parameter name.

Return

PicoUploadFileContainer

An instance of the uploaded file container or an empty container.

4. __get

Declaration

public function __get(
    string $name
) : PicoUploadFileContainer
{
}

Description

Magic method to handle dynamic property access.

Parameters

$name

The name of the property being accessed.

Return

PicoUploadFileContainer

An instance of the uploaded file container or an empty container.

5. __isset

Declaration

public function __isset(
    string $name
) : bool
{
}

Description

Check if an uploaded file exists for the given parameter name.

Parameters

$name

The parameter name.

Return

bool

True if the file exists; otherwise, false.

6. initMap

Declaration

private function initMap() : void
{
}

Description

Initialize the mapping of uploaded file names to their keys.

Return

void
7. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a string representation for debugging.

Return

string

JSON-encoded string of the uploaded file data.

MagicObject\File\PicoUploadFileContainer

Declaration

class PicoUploadFileContainer { }

Package

MagicObject\File

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a container for uploaded files.

This class manages the uploaded file information and provides methods to handle single or multiple file uploads.

Properties

1. values

Declaration

private array $values = array();

Description

Array to store information about uploaded files.

Methods

1. __construct

Declaration

public function __construct(
    array|null $file = null
)
{
}

Description

Constructor.

Initializes the container with uploaded file data.

Parameters

$file

An associative array containing file upload information.

2. isMultiple

Declaration

public function isMultiple() : bool
{
}

Description

Checks if multiple files were uploaded.

Return

bool

True if multiple files were uploaded; otherwise, false.

3. isExists

Declaration

public function isExists(
    int $index
) : bool
{
}

Description

Checks if a specific file exists in the upload.

Parameters

$index

The index of the uploaded file.

Return

bool

True if the file exists; otherwise, false.

4. getFileCount

Declaration

public function getFileCount() : int
{
}

Description

Gets the total number of uploaded files.

Return

int

The number of files uploaded.

5. getAll

Declaration

public function getAll() : PicoUploadFileItem[]
{
}

Description

Retrieves all uploaded files.

Return

PicoUploadFileItem[]

An array of PicoUploadFileItem objects representing uploaded files.

6. getItem

Declaration

public function getItem(
    int $index
) : array
{
}

Description

Gets information about a specific uploaded file.

Parameters

$index

The index of the uploaded file.

Return

array

An associative array containing information about the uploaded file.

7. __toString

Declaration

public function __toString() : string
{
}

Description

Converts the object to a string representation.

Return

string

A JSON-encoded string of the uploaded file information.

MagicObject\File\PicoUploadFileItem

Declaration

class PicoUploadFileItem { }

Package

MagicObject\File

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing an uploaded file item.

This class manages the information of an uploaded file and provides methods to interact with the file, such as copying or moving it to a destination path.

Properties

1. value

Declaration

private array $value = array();

Description

Array to store uploaded file information.

Methods

1. __construct

Declaration

public function __construct(
    array $file
)
{
}

Description

Constructor.

Initializes the PicoUploadFileItem with file data.

Parameters

$file

An associative array containing file upload information.

Throws

InvalidParameterException

if the provided file data is invalid.

2. copyTo

Declaration

public function copyTo(
    string $path
) : bool
{
}

Description

Copies the uploaded file to a specified destination path.

Parameters

$path

The target path where the file will be copied.

Return

bool

True on success; otherwise, false.

Throws

FileNotFoundException

if the temporary file is not found.

3. moveTo

Declaration

public function moveTo(
    string $path
) : bool
{
}

Description

Moves the uploaded file to a specified destination path.

Parameters

$path

The target path where the file will be moved.

Return

bool

True on success; otherwise, false.

Throws

FileNotFoundException

if the temporary file is not found.

4. getTmpName

Declaration

public function getTmpName() : string|null
{
}

Description

Gets the temporary file name.

Return

string|null

The temporary file name or null if not set.

5. getName

Declaration

public function getName() : string|null
{
}

Description

Gets the original file name.

Return

string|null

The original file name or null if not set.

6. getError

Declaration

public function getError() : mixed
{
}

Description

Gets the error associated with the file upload.

Return

mixed

The error code or null if not set.

7. getSize

Declaration

public function getSize() : int
{
}

Description

Gets the size of the uploaded file.

Return

int

The file size in bytes; returns 0 if not set.

8. getType

Declaration

public function getType() : string|null
{
}

Description

Gets the MIME type of the uploaded file.

Return

string|null

The MIME type or null if not set.

MagicObject\Generator\PicoColumnGenerator

Declaration

class PicoColumnGenerator { }

Package

MagicObject\Generator

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for generating column information from a database.

This class provides methods to retrieve a list of columns for a specified database table.

Methods

1. getColumnList

Declaration

public static function getColumnList(
    PicoDatabase $database,
    string $picoTableName
) : array
{
}

Description

Get the list of columns from a specified database table.

Parameters

$database

The database connection instance.

$picoTableName

The name of the table to retrieve columns from.

Return

array

An array of column names or an empty array if not applicable.

MagicObject\Generator\PicoDatabaseDump

Declaration

class PicoDatabaseDump { }

Package

MagicObject\Generator

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Database dump class for managing and generating SQL statements for table structures.

Properties

1. tableInfo

Declaration

protected PicoTableInfo $tableInfo;

Description

Table information

2. picoTableName

Declaration

protected string $picoTableName = '';

Description

Table name

3. columns

Declaration

protected array $columns = array();

Description

Columns

Methods

1. dumpStructure

Declaration

public function dumpStructure(
    MagicObject $entity,
    string $databaseType,
    bool $createIfNotExists = false,
    bool $dropIfExists = false,
    string $engine = 'InnoDB',
    string $charset = 'utf8mb4'
) : string
{
}

Description

Dump the structure of a table for the specified entity.

Parameters

$entity

Entity to be dumped

$databaseType

Target database type

$createIfNotExists

Add DROP TABLE IF EXISTS before create table

$dropIfExists

Add IF NOT EXISTS on create table

$engine

Storage engine (for MariaDB and MySQL)

$charset

Default charset

Return

string

SQL statement for creating table structure

2. dumpStructureTable

Declaration

public function dumpStructureTable(
    PicoTableInfo $tableInfo,
    string $databaseType,
    bool $createIfNotExists = false,
    bool $dropIfExists = false,
    string $engine = 'InnoDB',
    string $charset = 'utf8mb4'
) : string
{
}

Description

Dump the structure of a specified table.

Parameters

$tableInfo

Table information

$databaseType

Database type

$createIfNotExists

Flag to add CREATE IF NOT EXISTS

$dropIfExists

Flag to add DROP IF EXISTS

$engine

Database engine

$charset

Charset

Return

string

SQL statement for creating table structure

3. getTableInfo

Declaration

public function getTableInfo(
    MagicObject $entity
) : PicoTableInfo|null
{
}

Description

Get the table information for the specified entity.

Parameters

$entity

Entity

Return

PicoTableInfo|null

Table information or null if entity is null

4. updateQueryAlterTableAddColumn

Declaration

public function updateQueryAlterTableAddColumn(
    string $query,
    string $lastColumn,
    string $databaseType
) : string
{
}

Description

Update the query for adding a column to a table.

Parameters

$query

Query string

$lastColumn

Last column name

$databaseType

Database type

Return

string

Updated query string

5. updateQueryAlterTableNullable

Declaration

public function updateQueryAlterTableNullable(
    string $query,
    array $entityColumn
) : string
{
}

Description

Update the query to set a column as nullable.

Parameters

$query

Query string

$entityColumn

Entity column information

Return

string

Updated query string

6. updateQueryAlterTableDefaultValue

Declaration

public function updateQueryAlterTableDefaultValue(
    string $query,
    array $entityColumn
) : string
{
}

Description

Update the query to set a default value for a column.

Parameters

$query

Query string

$entityColumn

Entity column information

Return

string

Updated query string

7. createAlterTableAdd

Declaration

public function createAlterTableAdd(
    MagicObject|MagicObject[] $entity,
    PicoDatabase|null $database = null,
    bool $createIfNotExists = false,
    bool $dropIfExists = false,
    bool $forceCreateNewTable = false
) : string[]
{
}

Description

Create an ALTER TABLE ADD COLUMN query for the specified entity or entities.

This method generates SQL queries to add new columns to a table. It supports adding columns from either a single entity or an array of entities. Depending on whether a single entity or multiple entities are provided, the method delegates query generation to different helper methods. If the $forceCreateNewTable flag is set to true, the method will generate a CREATE TABLE query instead of an ALTER TABLE query, effectively creating a new table with the specified columns.

Parameters

$entity

A single entity or an array of entities representing the columns to be added.

$database

The database connection used to fetch the current table schema. If null,

$createIfNotExists

Flag indicating whether to generate a CREATE TABLE query if the table does not exist.

$dropIfExists

Flag indicating whether to generate a DROP TABLE query if the table already exists,

$forceCreateNewTable

Flag indicating whether to generate a CREATE TABLE query instead of ALTER TABLE,

Return

string[]

An array of SQL queries (either ALTER TABLE or CREATE TABLE) to add the columns.

8. getDatabase

Declaration

private function getDatabase(
    PicoDatabase|null $database,
    MagicObject[] $entities
) : PicoDatabase
{
}

Description

Get the database connection.

Parameters

$database

Database connection

$entities

Entities

Return

PicoDatabase

Database connection

9. getDatabaseType

Declaration

public function getDatabaseType(
    PicoDatabase $database
) : string
{
}

Description

Get the database type.

Parameters

$database

Database connection

Return

string

Database type

10. getTableName

Declaration

private function getTableName(
    string|null $tableName,
    PicoTableInfo $tableInfo
) : string
{
}

Description

Get the table name.

Parameters

$tableName

Table name

$tableInfo

Table information

Return

string

Table name

11. createQueryAlterTable

Declaration

public function createQueryAlterTable(
    string $tableName,
    string $columnName,
    string $columnType
) : string
{
}

Description

Create an ALTER TABLE query to add a column.

Parameters

$tableName

Table name

$columnName

Column name

$columnType

Column type

Return

string

SQL ALTER TABLE query

12. getColumnNameList

Declaration

public function getColumnNameList(
    MagicObject[] $entities
) : string[]
{
}

Description

Get a list of column names from multiple entities.

This method retrieves the table information for each entity, extracts the columns, and merges them into a single list.

Parameters

$entities

Array of entities to process.

Return

string[]

List of column names from all entities.

13. createAlterTableAddFromEntities

Declaration

public function createAlterTableAddFromEntities(
    MagicObject[] $entities,
    string|null $tableName = null,
    PicoDatabase|null $database = null,
    bool $createIfNotExists = false,
    bool $dropIfExists = false,
    bool $forceCreateNewTable = false
) : string[]
{
}

Description

Create a list of ALTER TABLE ADD COLUMN queries from multiple entities.

This method generates SQL queries to add new columns to an existing table based on the provided entities. It checks the current database schema and compares it with the provided entity information, generating the necessary ALTER TABLE queries. If columns already exist in the database, they will be skipped unless the forceCreateNewTable flag is set to true, in which case a CREATE TABLE query will be generated to create the table (and columns) from scratch, even if the columns already exist.

Parameters

$entities

An array of entity objects representing the columns to be added. Each entity contains

$tableName

The name of the table to alter. If null, the table name will be derived from the entities.

$database

The database connection used to fetch the current table schema. If null, it will

$createIfNotExists

Flag indicating whether a CREATE TABLE query should be generated if the table does not exist.

$dropIfExists

Flag indicating whether a DROP TABLE query should be generated if the table already exists,

$forceCreateNewTable

Flag indicating whether to generate a CREATE TABLE query instead of an ALTER TABLE query.

Return

string[]

An array of SQL queries (either ALTER TABLE or CREATE TABLE) to add the columns. Each query is a string

14. createAlterTableAddFromEntity

Declaration

public function createAlterTableAddFromEntity(
    MagicObject $entity,
    bool $forceCreateNewTable = false
) : string[]
{
}

Description

Create a list of ALTER TABLE ADD COLUMN queries or a CREATE TABLE query from a single entity.

This method generates SQL queries to add new columns to a table based on the provided entity. It compares the current database schema with the entity's column definitions. If the columns do not already exist, it generates the necessary ALTER TABLE queries. However, if the forceCreateNewTable flag is set to true, a CREATE TABLE query will be generated instead of ALTER TABLE, effectively creating the table and columns from scratch even if the columns already exist in the database.

Parameters

$entity

The entity representing the table and its columns to be added.

$forceCreateNewTable

Flag indicating whether to generate a CREATE TABLE query, even if the table and

Return

string[]

An array of SQL queries (either ALTER TABLE or CREATE TABLE) to add the columns. Each query

15. addPrimaryKey

Declaration

private function addPrimaryKey(
    string[] $queryAlter,
    PicoTableInfoExtended $tableInfo,
    string $tableName,
    string[] $createdColumns
) : string[]
{
}

Description

Add primary key constraints to the ALTER TABLE queries.

Parameters

$queryAlter

Existing ALTER TABLE queries

$tableInfo

Table information

$tableName

Table name

$createdColumns

List of created columns

Return

string[]

Updated ALTER TABLE queries

16. addAutoIncrement

Declaration

private function addAutoIncrement(
    string[] $queryAlter,
    PicoTableInfoExtended $tableInfo,
    string $tableName,
    string[] $createdColumns,
    string $databaseType
) : string[]
{
}

Description

Add auto-increment functionality to specified columns.

Parameters

$queryAlter

Existing ALTER TABLE queries

$tableInfo

Table information

$tableName

Table name

$createdColumns

List of created columns

$databaseType

Database type

Return

string[]

Updated ALTER TABLE queries

17. getAutoIncrementKey

Declaration

public function getAutoIncrementKey(
    PicoTableInfo $tableInfo
) : string[]
{
}

Description

Get the auto-increment keys from table information.

Parameters

$tableInfo

Table information

Return

string[]

List of auto-increment keys

18. getMergedTableInfoOld

Declaration

public function getMergedTableInfoOld(
    MagicObject[] $entities
) : PicoTableInfoExtended
{
}

Description

Merge multiple entities' table information.

Parameters

$entities

Entities

Return

PicoTableInfoExtended

Merged table information

19. getMergedTableInfo

Declaration

public function getMergedTableInfo(
    MagicObject[] $entities
) : PicoTableInfoExtended
{
}

Description

Get merged table information from multiple entities.

Parameters

$entities

Entities

Return

PicoTableInfoExtended

Merged table information

20. dumpData

Declaration

public function dumpData(
    MagicObject|PicoPageData $data,
    string $databaseType,
    MagicObject|null $entity = null,
    int $maxRecord = 100,
    callable|null $callbackFunction = null
) : string
{
}

Description

Dumps data into SQL format.

This method processes the provided data and converts it into SQL format suitable for the specified database type. It requires a model instance to retrieve table information if not already set.

WARNING: Use a different instance to dump different entities to avoid conflicts.

Parameters

$data

Data to be dumped into SQL format.

$databaseType

Target database type (e.g., MySQL, MariaDB).

$entity

Optional model instance used to retrieve table information

$maxRecord

Maximum number of records to process in a single query (default is 100).

$callbackFunction

Optional callback function to process the generated SQL

Return

string

SQL dump as a string; returns an empty string for unsupported database types.

MagicObject\Generator\PicoDtoGenerator

Declaration

class PicoDtoGenerator { }

Package

MagicObject\Generator

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

DTO generator for creating Data Transfer Objects (DTOs) from database tables.

This class helps in generating DTOs that can be used for transferring data via APIs or for serialization into files or databases.

Properties

1. database

Declaration

protected PicoDatabase $database;

Description

Database connection instance.

2. baseDir

Declaration

protected string $baseDir = '';

Description

Base directory for saving generated DTO files.

3. baseNamespaceDto

Declaration

protected string $baseNamespaceDto = '';

Description

Base namespace for the generated DTOs.

4. tableName

Declaration

protected string $tableName = '';

Description

Table name to generate DTO for.

5. entityName

Declaration

protected string $entityName;

Description

Name of the entity associated with the DTO.

6. dtoName

Declaration

protected string $dtoName;

Description

Name of the DTO being generated.

7. baseNamespaceEntity

Declaration

protected string $baseNamespaceEntity;

Description

Base namespace for the entity.

8. prettify

Declaration

protected bool $prettify = false;

Description

Flag to indicate whether to prettify the output.

Methods

1. __construct

Declaration

public function __construct(
    PicoDatabase $database,
    string $baseDir,
    string $tableName,
    string $baseNamespaceDto,
    string $dtoName,
    string $baseNamespaceEntity,
    string|null $entityName = null,
    bool $prettify = false
)
{
}

Description

Constructor for the DTO generator.

Parameters

$database

Database connection

$baseDir

Base directory for generated files

$tableName

Table name for DTO generation

$baseNamespaceDto

Base namespace for DTOs

$dtoName

Name of the DTO

$baseNamespaceEntity

Base namespace for the entity

$entityName

Name of the entity (optional)

$prettify

Flag to prettify output (default: false)

2. createProperty

Declaration

protected function createProperty(
    array $typeMap,
    string $columnName,
    string $columnType,
    bool $prettifyLabel = true
) : string
{
}

Description

Create a property with appropriate documentation.

This method generates a PHP property with a docblock based on the provided column name and type. The docblock includes annotations like @Label to describe the property and @var to specify the data type of the property. It is used to automatically generate well-documented properties based on database column information.

Parameters

$typeMap

Mapping of database types to PHP types (e.g., 'int' => 'integer').

$columnName

Name of the column from the database.

$columnType

Type of the column from the database (e.g., 'varchar', 'int').

$prettifyLabel

Whether to modify the column name into a more readable label (default is true).

Return

string

PHP code for the property with a docblock, including the appropriate annotations like

3. getPropertyName

Declaration

protected function getPropertyName(
    string $name,
    bool $prettifyLabel = true
) : string
{
}

Description

Get a descriptive name for the property based on the column name. The column name is converted to a formatted property name, where each part of the column name (split by underscores) is capitalized. Special cases such as "Id" and "Ip" are handled to be formatted as "ID" and "IP", respectively.

Parameters

$name

Original column name (e.g., 'user_id', 'user_ip')

$prettifyLabel

Whether to replace 'Id' with 'ID' and 'Ip' with 'IP'

Return

string

Formatted property name (e.g., 'User ID', 'User IP')

4. getDataType

Declaration

protected function getDataType(
    array $typeMap,
    string $columnType
) : string
{
}

Description

Determine the PHP data type corresponding to the column type.

Parameters

$typeMap

Mapping of database types to PHP types

$columnType

Database column type

Return

string

Corresponding PHP data type

5. createValueOf

Declaration

protected function createValueOf(
    string $picoTableName,
    array $rows
) : string
{
}

Description

Create a static method to construct the DTO from the entity.

Parameters

$picoTableName

Table name

$rows

Data rows from the database

Return

string

PHP code for the valueOf method

6. getTypeMap

Declaration

protected function getTypeMap() : array
{
}

Description

Get a mapping of database types to PHP types.

Return

array

Associative array of type mappings

7. generate

Declaration

public function generate() : int
{
}

Description

Generate the DTO and save it to a file.

Return

int

Result of file write operation (number of bytes written or false on failure)

MagicObject\Generator\PicoEntityGenerator

Declaration

class PicoEntityGenerator { }

Package

MagicObject\Generator

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

PicoEntityGenerator is an entity generator for automatically generating PHP code. This class is optimized for the MariaDB database. Users must provide appropriate parameters so that the entity class can be directly used in the application.

Constants

const TYPE_CHARACTER_VARYING = "character varying";
const TYPE_TINYINT_1 = "tinyint(1)";
const TYPE_VARCHAR_255 = "varchar(255)";
const TYPE_TIMESTAMP_WITH_TIME_ZONE = "timestamp with time zone";
const TYPE_TIMESTAMP_WITHOUT_TIME_ZONE = "timestamp without time zone";

Properties

1. database

Declaration

protected PicoDatabase $database;

Description

Database connection instance.

2. baseDir

Declaration

protected string $baseDir = '';

Description

Base directory for generated files.

3. baseNamespace

Declaration

protected string $baseNamespace = '';

Description

Base namespace for the entity classes.

4. tableName

Declaration

protected string $tableName = '';

Description

Table name for which the entity is generated.

5. entityName

Declaration

protected string $entityName;

Description

Name of the entity being generated.

6. prettify

Declaration

protected boolean $prettify = false;

Description

Flag indicating whether to prettify the output.

Methods

1. __construct

Declaration

public function __construct(
    PicoDatabase $database,
    string $baseDir,
    string $tableName,
    string $baseNamespace,
    string|null $entityName = null,
    bool $prettify = false
)
{
}

Description

Constructor for the PicoEntityGenerator class.

Parameters

$database

Database connection

$baseDir

Base directory for generated files

$tableName

Table name for entity generation

$baseNamespace

Base namespace for the entity classes

$entityName

Name of the entity (optional)

$prettify

Flag to prettify output (default: false)

2. createProperty

Declaration

protected function createProperty(
    array $typeMap,
    array $columnMap,
    array $row,
    string[]|null $nonupdatables = null,
    bool $prettifyLabel = true
) : string
{
}

Description

Generates a PHP property with a docblock based on database column metadata.

This method creates a property for a PHP class, including annotations such as @Id, @GeneratedValue, @NotNull, and @Column, derived from the given database column details. It supports column attributes like primary key, auto-increment, nullable, and default value, and provides type mappings based on the provided database-to-PHP type mappings.

Parameters

$typeMap

Database-to-PHP type mappings (e.g., 'int' => 'integer').

$columnMap

Database column-to-type mappings (e.g., 'int' => 'INTEGER').

$row

Column metadata from the database (e.g., from information_schema.columns).

$nonupdatables

List of non-updatable columns, or null if none.

$prettifyLabel

Whether to convert column names to human-readable labels (default is true).

Return

string

PHP code for the property with a docblock, ready to be inserted into a class.

3. getPropertyName

Declaration

protected function getPropertyName(
    string $name,
    bool $prettifyLabel = true
) : string
{
}

Description

Get a descriptive name for the property based on the column name. The column name is converted to a formatted property name, where each part of the column name (split by underscores) is capitalized. Special cases such as "Id" and "Ip" are handled to be formatted as "ID" and "IP", respectively.

Parameters

$name

Original column name (e.g., 'user_id', 'user_ip')

$prettifyLabel

Whether to replace 'Id' with 'ID' and 'Ip' with 'IP'

Return

string

Formatted property name (e.g., 'User ID', 'User IP')

4. getColumnType

Declaration

protected function getColumnType(
    array $typeMap,
    string $columnType
) : string
{
}

Description

Get the corresponding PHP data type based on the column type.

Parameters

$typeMap

Mapping of database types to PHP types

$columnType

Database column type

Return

string

Corresponding PHP data type

5. getDataType

Declaration

protected function getDataType(
    array $typeMap,
    string $columnType
) : string
{
}

Description

Get the corresponding PHP data type based on the column type.

Parameters

$typeMap

Mapping of database types to PHP types

$columnType

Database column type

Return

string

Corresponding PHP data type

6. getDataLength

Declaration

protected function getDataLength(
    string $str
) : int
{
}

Description

Get the length of the column based on its definition.

Parameters

$str

Column definition containing length

Return

int

Length of the column

7. getTypeMap

Declaration

protected function getTypeMap() : array
{
}

Description

Get a mapping of database types to PHP types for MySQL, PostgreSQL, and SQLite.

This method returns an associative array that maps common database column types from MySQL, PostgreSQL, and SQLite to their corresponding PHP types. This mapping is useful for handling database type conversions when interacting with data in PHP.

The array provides mappings for numeric types, string types, boolean types, date/time types, and special cases such as JSON and UUID. It helps in ensuring proper handling of database types across different database systems.

Return

array

Associative array of type mappings where the keys are database column types

8. getColumnMap

Declaration

public function getColumnMap() : array
{
}

Description

Get a mapping of database column types to MySQL equivalents.

Provides a conversion map from various database column types to MySQL-compatible column types, useful for data migrations or type compatibility.

Return

array

Associative array with column types from other databases mapped to MySQL types.

9. getColumnMapByType

Declaration

public function getColumnMapByType(
    string $targetDb
) : array
{
}

Description

Get a mapping of database column types to target database equivalents.

Converts column types from one database (MySQL, PostgreSQL, SQLite) to another, supporting data migrations and compatibility.

Parameters

$targetDb

The target database type ('mysql', 'postgresql', or 'sqlite').

Return

array

Associative array of column types from other databases mapped to the target database types.

10. generate

Declaration

public function generate(
    string[]|null $nonupdatables = null,
    bool $prettifyLabel = true
) : int|false
{
}

Description

Generates an entity class based on database table metadata and saves it to a file.

This method creates a PHP class that maps to a database table, including properties for each column. It supports ORM annotations (e.g., @Entity, @Table, @JSON) and handles non-updatable columns. Optionally, it can prettify property names for human readability.

Parameters

$nonupdatables

List of non-updatable columns, or null if none.

$prettifyLabel

Whether to prettify column names into human-readable labels (default is true).

Return

int|false

The number of bytes written to the file, or false on failure.

MagicObject\Geometry\Area

Declaration

class Area { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class Area

Represents a geometric area defined by various shapes such as rectangles, triangles, polygons, and circles. This class encapsulates properties related to the shape, its coordinates, and any associated attributes or hyperlinks. It also provides methods to calculate coordinates based on the shape type, apply zoom factors, and generate an HTML representation for use in maps or similar applications.

Properties

1. shape

Declaration

public string $shape;

Description

Shape type of the area.

2. coords

Declaration

public float[] $coords = array();

Description

Coordinates defining the shape.

3. href

Declaration

public string $href;

Description

Hyperlink reference associated with the area.

4. attributes

Declaration

public string[] $attributes;

Description

Additional attributes for the area.

5. zoom

Declaration

public float $zoom = 1;

Description

Zoom factor for the area.

Methods

1. __construct

Declaration

public function __construct(
    mixed $object,
    float $zoom = 1,
    string|null $href = null,
    string[]|null $attributes = null
)
{
}

Description

Constructor for the Area class.

Parameters

$object

One of Rectangle, Triangle, Polygon, or Circle

$zoom

Zoom factor (default: 1)

$href

Hyperlink reference (optional)

$attributes

Additional attributes (optional)

2. coordsFromRectangle

Declaration

public function coordsFromRectangle(
    Rectangle $object
) : float[]
{
}

Description

Get coordinates from a rectangle.

Parameters

$object

Rectangle object

Return

float[]

Coordinates of the rectangle

3. coordsFromTriangle

Declaration

public function coordsFromTriangle(
    Triangle $object
) : float[]
{
}

Description

Get coordinates from a triangle.

Parameters

$object

Triangle object

Return

float[]

Coordinates of the triangle

4. coordsFromPolygon

Declaration

public function coordsFromPolygon(
    Polygon $object
) : float[]
{
}

Description

Get coordinates from a polygon.

Parameters

$object

Polygon object

Return

float[]

Coordinates of the polygon

5. coordsFromCircle

Declaration

public function coordsFromCircle(
    Circle $object
) : float[]
{
}

Description

Get coordinates from a circle.

Parameters

$object

Circle object

Return

float[]

Coordinates of the circle

6. getCoords

Declaration

public function getCoords(
    float $zoom = 1
) : float[]
{
}

Description

Get coordinates with optional zoom factor.

Parameters

$zoom

Zoom factor (default: 1)

Return

float[]

Adjusted coordinates

7. getHTML

Declaration

public function getHTML() : string
{
}

Description

Generate HTML representation of the area.

Return

string

HTML string for the area

8. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the area object to a string.

Return

string

HTML representation of the area

9. getZoom

Declaration

public function getZoom() : float
{
}

Description

Get the current zoom factor.

Return

float

Zoom factor

10. setZoom

Declaration

public function setZoom(
    float $zoom
) : self
{
}

Description

Set the zoom factor.

Parameters

$zoom

Zoom factor

Return

self

Returns the current instance for method chaining.

MagicObject\Geometry\Circle

Declaration

class Circle { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class Circle

Represents a circle defined by a center point and a radius. This class provides methods to calculate the circle's circumference and area, based on its radius. The circle is defined by its center coordinates (x, y) and its radius (r).

Properties

1. center

Declaration

public Point $center;

Description

Center point of the circle.

2. x

Declaration

public float $x = 0.0;

Description

x coordinate of the circle's center.

3. y

Declaration

public float $y = 0.0;

Description

y coordinate of the circle's center.

4. r

Declaration

public float $r = 0.0;

Description

Radius of the circle.

Methods

1. __construct

Declaration

public function __construct(
    float $x,
    float $y,
    float $r
)
{
}

Description

Constructor to initialize the Circle with x, y, and r.

Parameters

$x

x coordinate of the center

$y

y coordinate of the center

$r

Radius of the circle

2. getCircumference

Declaration

public function getCircumference() : float
{
}

Description

Get the circumference of the circle.

Return

float

Circumference of the circle

3. getArea

Declaration

public function getArea() : float
{
}

Description

Get the area of the circle.

Return

float

Area of the circle

MagicObject\Geometry\LatBounds

Declaration

class LatBounds { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class LatBounds

Represents a latitude bounding box defined by southwestern and northeastern latitude values. This class provides functionality to manage and calculate properties of latitude bounds, including checking for containment, intersections, and equality with other latitude bounds.

Properties

1. _swLat

Declaration

protected $_swLat;

Description

@var float The southwestern latitude value.

2. _neLat

Declaration

protected $_neLat;

Description

@var float The northeastern latitude value.

Methods

1. __construct

Declaration

public function __construct(
    float $swLat,
    float $neLat
)
{
}

Description

LatBounds constructor.

Parameters

$swLat

The southwestern latitude.

$neLat

The northeastern latitude.

2. getSw

Declaration

public function getSw() : float
{
}

Description

Get the southwestern latitude.

Return

float

The southwestern latitude.

3. getNe

Declaration

public function getNe() : float
{
}

Description

Get the northeastern latitude.

Return

float

The northeastern latitude.

4. getMidpoint

Declaration

public function getMidpoint() : float
{
}

Description

Calculate the midpoint latitude between the southwestern and northeastern latitudes.

Return

float

The midpoint latitude.

5. isEmpty

Declaration

public function isEmpty() : bool
{
}

Description

Check if the latitude bounds are empty (i.e., invalid).

Return

bool

True if the bounds are empty, false otherwise.

6. intersects

Declaration

public function intersects(
    LatBounds $latBounds
) : bool
{
}

Description

Determine if this LatBounds intersects with another LatBounds.

Parameters

$latBounds

The other LatBounds to check for intersection.

Return

bool

True if there is an intersection, false otherwise.

7. equals

Declaration

public function equals(
    LatBounds $latBounds
) : bool
{
}

Description

Check if this LatBounds is equal to another LatBounds within a certain margin of error.

Parameters

$latBounds

The other LatBounds to compare.

Return

bool

True if they are equal, false otherwise.

8. contains

Declaration

public function contains(
    float $lat
) : bool
{
}

Description

Check if a given latitude is contained within the bounds.

Parameters

$lat

The latitude to check.

Return

bool

True if the latitude is contained, false otherwise.

9. extend

Declaration

public function extend(
    float $lat
)
{
}

Description

Extend the bounds to include a new latitude.

If the bounds are empty, the latitude becomes both the southwestern and northeastern bounds. If the latitude is less than the southwestern bound, it updates the southwestern bound. If the latitude is greater than the northeastern bound, it updates the northeastern bound.

Parameters

$lat

The latitude to extend the bounds with.

MagicObject\Geometry\LatLng

Declaration

class LatLng { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class LatLng

Represents a geographical point defined by latitude and longitude values. This class provides methods to manage and manipulate geographic coordinates, including equality checks and string representations.

Properties

1. _lat

Declaration

protected $_lat;

Description

@var float The latitude value.

2. _lng

Declaration

protected $_lng;

Description

@var float The longitude value.

Methods

1. __construct

Declaration

public function __construct(
    float $lat,
    float $lng,
    bool $noWrap = false
)
{
}

Description

LatLng constructor.

Parameters

$lat

The latitude value.

$lng

The longitude value.

$noWrap

Whether to wrap the longitude value.

Throws

E_USER_ERROR

If the latitude or longitude is not a valid float.

2. getLat

Declaration

public function getLat() : float
{
}

Description

Get the latitude value.

Return

float

The latitude.

3. getLng

Declaration

public function getLng() : float
{
}

Description

Get the longitude value.

Return

float

The longitude.

4. equals

Declaration

public function equals(
    LatLng $latLng
) : bool
{
}

Description

Check if this LatLng is equal to another LatLng object within a certain margin of error.

Parameters

$latLng

The LatLng object to compare.

Return

bool

True if they are equal, false otherwise.

5. toString

Declaration

public function toString() : string
{
}

Description

Convert the LatLng object to a string representation.

Return

string

The string representation of the LatLng in the format "(lat, lng)".

6. toUrlValue

Declaration

public function toUrlValue(
    int $precision = 6
) : string
{
}

Description

Convert the LatLng object to a URL-friendly string value.

Parameters

$precision

The number of decimal places to round to (default: 6).

Return

string

The latitude and longitude values as a string.

MagicObject\Geometry\LatLngBounds

Declaration

class LatLngBounds { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class LatLngBounds

Represents a bounding box defined by southwest and northeast LatLng objects.

Properties

1. _latBounds

Declaration

protected $_latBounds;

Description

@var LatBounds The latitude bounds of the bounding box.

2. _lngBounds

Declaration

protected $_lngBounds;

Description

@var LngBounds The longitude bounds of the bounding box.

Methods

1. __construct

Declaration

public function __construct(
    LatLng|null $latLngSw = null,
    LatLng|null $tatLngNe = null
)
{
}

Description

LatLngBounds constructor.

Parameters

$latLngSw

The southwestern LatLng object.

$tatLngNe

The northeastern LatLng object.

Throws

E_USER_ERROR

If the provided LatLng objects are invalid.

2. getLatBounds

Declaration

public function getLatBounds() : LatBounds
{
}

Description

Get the latitude bounds.

Return

LatBounds

The latitude bounds of the bounding box.

3. getLngBounds

Declaration

public function getLngBounds() : LngBounds
{
}

Description

Get the longitude bounds.

Return

LngBounds

The longitude bounds of the bounding box.

4. getCenter

Declaration

public function getCenter() : LatLng
{
}

Description

Get the center point of the bounding box.

Return

LatLng

The center point as a LatLng object.

5. isEmpty

Declaration

public function isEmpty() : bool
{
}

Description

Check if the bounding box is empty.

Return

bool

True if the bounding box is empty, false otherwise.

6. getSouthWest

Declaration

public function getSouthWest() : LatLng
{
}

Description

Get the southwestern corner of the bounding box.

Return

LatLng

The southwestern corner as a LatLng object.

7. getNorthEast

Declaration

public function getNorthEast() : LatLng
{
}

Description

Get the northeastern corner of the bounding box.

Return

LatLng

The northeastern corner as a LatLng object.

8. toSpan

Declaration

public function toSpan() : LatLng
{
}

Description

Get the span of the bounding box as a LatLng object.

Return

LatLng

The span defined by the latitude and longitude differences.

9. toString

Declaration

public function toString() : string
{
}

Description

Convert the bounding box to a string representation.

Return

string

The string representation of the bounding box.

10. toUrlValue

Declaration

public function toUrlValue(
    int $precision = 6
) : string
{
}

Description

Convert the bounding box to a URL-friendly string value.

Parameters

$precision

The number of decimal places to round to.

Return

string

The southwest and northeast corner values as a string.

11. equals

Declaration

public function equals(
    LatLngBounds $latLngBounds
) : bool
{
}

Description

Check if this LatLngBounds is equal to another LatLngBounds object.

Parameters

$latLngBounds

The LatLngBounds object to compare.

Return

bool

True if they are equal, false otherwise.

12. intersects

Declaration

public function intersects(
    LatLngBounds $latLngBounds
) : bool
{
}

Description

Check if this LatLngBounds intersects with another LatLngBounds.

Parameters

$latLngBounds

The LatLngBounds to check for intersection.

Return

bool

True if they intersect, false otherwise.

13. union

Declaration

public function union(
    LatLngBounds $latLngBounds
) : $this
{
}

Description

Extend this bounding box to include another LatLngBounds.

Parameters

$latLngBounds

The LatLngBounds to extend with.

Return

$this

The current instance for method chaining.

14. contains

Declaration

public function contains(
    LatLng $latLng
) : bool
{
}

Description

Check if this LatLngBounds contains a specific LatLng point.

Parameters

$latLng

The LatLng point to check for containment.

Return

bool

True if the point is contained, false otherwise.

15. extend

Declaration

public function extend(
    LatLng $latLng
) : $this
{
}

Description

Extend the bounding box to include a new LatLng point.

Parameters

$latLng

The LatLng point to extend with.

Return

$this

The current instance for method chaining.

MagicObject\Geometry\Line

Declaration

class Line { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a Line with two Point objects.

This class defines a Line in a 2D space represented by two endpoints, Point A and Point B. It provides methods to calculate the length of the line and ensure the endpoints are valid Point instances.

Properties

1. a

Declaration

public Point $a;

Description

Point A.

2. b

Declaration

public Point $b;

Description

Point B.

Methods

1. __construct

Declaration

public function __construct(
    Point $a,
    Point $b
)
{
}

Description

Constructor to initialize the Line with two Point objects.

Parameters

$a

Point A.

$b

Point B.

Throws

InvalidArgumentException

If the parameters are not instances of Point.

2. getLength

Declaration

public function getLength() : float
{
}

Description

Method to calculate the length of the line.

This method calculates the Euclidean distance between Point A and Point B.

Return

float

The length of the line between Point A and Point B.

MagicObject\Geometry\LngBounds

Declaration

class LngBounds { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class LngBounds

Represents a longitudinal bounding range defined by southwest and northeast longitude values.

Properties

1. _swLng

Declaration

protected $_swLng;

Description

@var float The southwestern longitude value.

2. _neLng

Declaration

protected $_neLng;

Description

@var float The northeastern longitude value.

Methods

1. __construct

Declaration

public function __construct(
    float $swLng,
    float $neLng
)
{
}

Description

LngBounds constructor.

Parameters

$swLng

The southwestern longitude value.

$neLng

The northeastern longitude value.

2. getSw

Declaration

public function getSw() : float
{
}

Description

Get the southwestern longitude.

Return

float

The southwestern longitude value.

3. getNe

Declaration

public function getNe() : float
{
}

Description

Get the northeastern longitude.

Return

float

The northeastern longitude value.

4. getMidpoint

Declaration

public function getMidpoint() : float
{
}

Description

Get the midpoint of the longitude bounds.

Return

float

The midpoint longitude value.

5. isEmpty

Declaration

public function isEmpty() : bool
{
}

Description

Check if the bounds are empty.

Return

bool

True if the bounds are empty, false otherwise.

6. intersects

Declaration

public function intersects(
    LngBounds $lngBounds
) : bool
{
}

Description

Check if this LngBounds intersects with another LngBounds.

Parameters

$lngBounds

The LngBounds to check for intersection.

Return

bool

True if they intersect, false otherwise.

7. equals

Declaration

public function equals(
    LngBounds $lngBounds
) : bool
{
}

Description

Check if this LngBounds is equal to another LngBounds.

Parameters

$lngBounds

The LngBounds object to compare.

Return

bool

True if they are equal, false otherwise.

8. contains

Declaration

public function contains(
    float $lng
) : bool
{
}

Description

Check if a given longitude is contained within the bounds.

Parameters

$lng

The longitude to check.

Return

bool

True if the longitude is contained, false otherwise.

9. extend

Declaration

public function extend(
    float $lng
) : void
{
}

Description

Extend the bounds to include a new longitude.

Parameters

$lng

The longitude to extend the bounds with.

Return

void

MagicObject\Geometry\Map

Declaration

class Map { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a Map containing multiple Areas.

This class manages a collection of Area objects, allowing for the addition and retrieval of areas. It can be initialized with an optional array of Area objects.

Properties

1. areas

Declaration

private Area[] $areas = array();

Description

Areas in the map.

Methods

1. __construct

Declaration

public function __construct(
    Area[]|null $areas = null
)
{
}

Description

Constructor to initialize the Map with optional areas.

Parameters

$areas

An array of Area objects to initialize the map with.

2. addArea

Declaration

public function addArea(
    Area $area
) : self
{
}

Description

Add an area to the map.

This method appends a new Area object to the map's collection of areas.

Parameters

$area

Area to add

Return

self

Returns the current instance for method chaining.

3. getAreas

Declaration

public function getAreas() : Area[]
{
}

Description

Get all areas in the map.

This method returns an array of Area objects contained in the map.

Return

Area[]

An array of Area objects

MagicObject\Geometry\NodeAttribute

Declaration

class NodeAttribute { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing node attributes.

This class stores a collection of attribute values associated with a node. It provides methods for initialization and converting the attributes to a string representation, suitable for use in contexts such as HTML attributes.

Properties

1. values

Declaration

private string[] $values = array();

Description

Values of the node attributes.

Methods

1. __construct

Declaration

public function __construct(
    string[] $values
)
{
}

Description

Constructor to initialize the NodeAttribute with values.

Parameters

$values

An array of attribute values.

2. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the node attributes to a string representation.

This method returns the attributes in a format suitable for inclusion in HTML tags, where each attribute is represented as key="value".

Return

string

A string representation of the node attributes.

MagicObject\Geometry\Point

Declaration

class Point { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a Point with x and y coordinates.

This class defines a Point in a 2D Cartesian coordinate system, allowing for the representation of its position and the calculation of distances to other Points.

Properties

1. x

Declaration

public float $x = 0.0;

Description

X coordinate.

2. y

Declaration

public float $y = 0.0;

Description

Y coordinate.

Methods

1. __construct

Declaration

public function __construct(
    float $x,
    float $y
)
{
}

Description

Constructor to initialize the Point with x and y coordinates.

Parameters

$x

X coordinate.

$y

Y coordinate.

2. distanceFrom

Declaration

public function distanceFrom(
    Point $p
) : float
{
}

Description

Calculate the distance between this Point and another Point.

This method computes the Euclidean distance between the current Point and another Point provided as an argument.

Parameters

$p

Another Point.

Return

float

The distance between the two Points.

Throws

InvalidArgumentException

If the argument is not of type Point.

3. distanceTo

Declaration

public function distanceTo(
    Point $p
) : float
{
}

Description

Calculate the distance between this Point and another Point.

This method serves as an alias to distanceFrom for better readability.

Parameters

$p

Another Point.

Return

float

The distance between the two Points.

MagicObject\Geometry\Polygon

Declaration

class Polygon { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a polygon defined by a series of points.

This class allows for the creation and manipulation of polygons, including adding points, clearing the polygon, and calculating its area and circumference.

Properties

1. points

Declaration

private Point[] $points = array();

Description

Points that make up the polygon.

Methods

1. __construct

Declaration

public function __construct(
    Point[] $points = array ( )
)
{
}

Description

Constructor to initialize the Polygon with an array of Points.

Parameters

$points

Initial points for the polygon.

2. addPoint

Declaration

public function addPoint(
    Point $point
) : self
{
}

Description

Add a point to the polygon.

Parameters

$point

Point to add.

Return

self

Returns the current instance for method chaining.

3. clearPolygon

Declaration

public function clearPolygon() : self
{
}

Description

Clear all points from the polygon.

This method removes all points currently defined for the polygon.

Return

self

Returns the current instance for method chaining.

4. getArea

Declaration

public function getArea() : float
{
}

Description

Calculate the area of the polygon using the Shoelace formula.

Return

float

The area of the polygon.

Throws

InvalidPolygonException

If the polygon has fewer than 3 points.

5. getCircumference

Declaration

public function getCircumference() : float
{
}

Description

Calculate the circumference of the polygon.

This method computes the total length of the polygon's edges.

Return

float

The circumference of the polygon.

Throws

InvalidPolygonException

If the polygon has fewer than 2 points.

6. getPoints

Declaration

public function getPoints() : Point[]
{
}

Description

Get the points of the polygon.

Return

Point[]

An array of Point objects that define the polygon.

MagicObject\Geometry\Rectangle

Declaration

class Rectangle { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a rectangle defined by two Point objects.

This class represents a rectangle using its bottom-left and top-right corner points. It provides methods to calculate the area and circumference (perimeter) of the rectangle by utilizing a Polygon representation of the rectangle's corners.

Properties

1. a

Declaration

public Point $a;

Description

Bottom-left corner point of the rectangle.

2. b

Declaration

public Point $b;

Description

Top-right corner point of the rectangle.

3. polygon

Declaration

public Polygon $polygon;

Description

Polygon representation of the rectangle.

Methods

1. __construct

Declaration

public function __construct(
    Point $a,
    Point $b
)
{
}

Description

Constructor to initialize the Rectangle with two Point objects.

Parameters

$a

Bottom-left corner point.

$b

Top-right corner point.

2. getArea

Declaration

public function getArea() : float
{
}

Description

Calculate the area of the rectangle.

Return

float

The area of the rectangle.

Throws

InvalidPolygonException

If the polygon is invalid.

3. getCircumference

Declaration

public function getCircumference() : float
{
}

Description

Get the circumference (perimeter) of the rectangle.

Return

float

The circumference of the rectangle.

Throws

InvalidPolygonException

If the polygon is invalid.

MagicObject\Geometry\SphericalGeometry

Declaration

class SphericalGeometry { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Static class SphericalGeometry

Provides utility functions for computing geodesic angles, distances, areas, and other spherical geometry calculations.

Constants

const EQUALS_MARGIN_ERROR = 1.0E-9;
const EARTH_RADIUS = 6378137;

Methods

1. getEarthRadius

Declaration

public static function getEarthRadius() : float
{
}

Description

Get the Earth's radius.

Return

float

The Earth's radius in meters.

2. computeBounds

Declaration

public static function computeBounds(
    LatLng $latLng,
    int|float $radius
) : LatLngBounds
{
}

Description

Computes a bounding rectangle (LatLngBounds instance) from a point and a given radius.

Reference: http://www.movable-type.co.uk/scripts/latlong-db.html

Parameters

$latLng

The center point as a LatLng object.

$radius

The radius in meters.

Return

LatLngBounds

The computed bounding rectangle.

3. computeHeading

Declaration

public static function computeHeading(
    LatLng $fromLatLng,
    LatLng $toLatLng
) : float
{
}

Description

Computes the heading from one LatLng to another.

Parameters

$fromLatLng

The starting LatLng.

$toLatLng

The destination LatLng.

Return

float

The heading in degrees from the starting point to the destination.

4. computeOffset

Declaration

public static function computeOffset(
    LatLng $fromLatLng,
    float $distance,
    float $heading
) : LatLng
{
}

Description

Computes a new LatLng based on a starting point, distance, and heading.

Parameters

$fromLatLng

The starting LatLng.

$distance

The distance to move, in meters.

$heading

The direction to move, in degrees.

Return

LatLng

The new LatLng after the offset.

5. containsLocation

Declaration

public static function containsLocation(
    object $point,
    object $polygon
) : bool
{
}

Description

Determines whether a point is contained within a polygon.

Parameters

$point

A point object with x() and y() methods for longitude and latitude.

$polygon

A polygon object with an exteriorRing() method.

Return

bool

True if the point is inside the polygon, false otherwise.

6. interpolate

Declaration

public static function interpolate(
    LatLng $fromLatLng,
    LatLng $toLatLng,
    float $fraction
) : LatLng
{
}

Description

Interpolates between two LatLng points based on a fraction.

Parameters

$fromLatLng

The starting LatLng.

$toLatLng

The ending LatLng.

$fraction

A fraction between 0 and 1.

Return

LatLng

The interpolated LatLng.

7. computeDistanceBetween

Declaration

public static function computeDistanceBetween(
    LatLng $latLng1,
    LatLng $latLng2
) : float
{
}

Description

Computes the distance between two LatLng points.

Parameters

$latLng1

The first LatLng point.

$latLng2

The second LatLng point.

Return

float

The distance in yards.

8. computeLength

Declaration

public static function computeLength(
    LatLng[] $latLngsArray
) : float
{
}

Description

Computes the total length of a series of LatLng points.

Parameters

$latLngsArray

An array of LatLng points.

Return

float

The total length in yards.

9. computeArea

Declaration

public static function computeArea(
    LatLng[] $latLngsArray
) : float
{
}

Description

Computes the area of a polygon defined by a series of LatLng points.

Parameters

$latLngsArray

An array of LatLng points defining the polygon.

Return

float

The area in square meters.

10. computeSignedArea

Declaration

public static function computeSignedArea(
    LatLng[] $latLngsArray,
    bool $signed = true
) : float
{
}

Description

Computes the signed area of a polygon defined by a series of LatLng points.

Parameters

$latLngsArray

An array of LatLng points defining the polygon.

$signed

Whether to return a signed area.

Return

float

The signed area in square meters.

11. clampLatitude

Declaration

public static function clampLatitude(
    float $lat
) : float
{
}

Description

Clamps a latitude value to be within valid bounds.

Parameters

$lat

The latitude to clamp.

Return

float

The clamped latitude value.

12. wrapLongitude

Declaration

public static function wrapLongitude(
    float $lng
) : float
{
}

Description

Wraps a longitude value to be within valid bounds.

Parameters

$lng

The longitude to wrap.

Return

float

The wrapped longitude value.

13. _computeDistanceInRadiansBetween

Declaration

protected static function _computeDistanceInRadiansBetween(
    LatLng $latLng1,
    LatLng $latLng2
) : float
{
}

Description

Computes the great circle distance (in radians) between two points. Uses the Haversine formula.

Parameters

$latLng1

The first LatLng point.

$latLng2

The second LatLng point.

Return

float

The distance in radians.

14. _computeSphericalExcess

Declaration

protected static function _computeSphericalExcess(
    LatLng $latLng1,
    LatLng $latLng2,
    LatLng $latLng3,
    bool $signed
) : float
{
}

Description

Computes the spherical excess using L'Huilier's Theorem.

Parameters

$latLng1

The first vertex of the triangle.

$latLng2

The second vertex of the triangle.

$latLng3

The third vertex of the triangle.

$signed

Whether to return a signed value.

Return

float

The spherical excess.

MagicObject\Geometry\Triangle

Declaration

class Triangle { }

Package

MagicObject\Geometry

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class representing a triangle defined by three Point objects.

This class represents a triangle in a 2D space using three vertices. It provides methods to calculate the lengths of the sides and the area using Heron's formula.

Properties

1. a

Declaration

public Point $a;

Description

Vertex A of the triangle.

2. b

Declaration

public Point $b;

Description

Vertex B of the triangle.

3. c

Declaration

public Point $c;

Description

Vertex C of the triangle.

4. sa

Declaration

public float $sa;

Description

Length of side opposite to vertex A.

5. sb

Declaration

public float $sb;

Description

Length of side opposite to vertex B.

6. sc

Declaration

public float $sc;

Description

Length of side opposite to vertex C.

Methods

1. __construct

Declaration

public function __construct(
    Point $a,
    Point $b,
    Point $c
)
{
}

Description

Constructor to initialize the Triangle with three Point objects.

Parameters

$a

The first vertex of the triangle.

$b

The second vertex of the triangle.

$c

The third vertex of the triangle.

2. getArea

Declaration

public function getArea() : float
{
}

Description

Calculate the area of the triangle using Heron's formula.

Return

float

The area of the triangle.

MagicObject\Language\PicoEntityLanguage

Declaration

class PicoEntityLanguage { }

Package

MagicObject\Language

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Entity Language Class

This class manages entity language configurations, including loading labels and handling different language options.

Constants

const ANNOTATION_TABLE = "Table";
const ANNOTATION_LANGUAGE = "Language";

Properties

2. _currentLanguage

Declaration

private string $_currentLanguage;

Description

Current language code.

3. _lableLanguage

Declaration

private PicoLanguage[] $_lableLanguage = array();

Description

Array of PicoLanguage objects.

4. _tableIdentity

Declaration

private PicoGenericObject $_tableIdentity;

Description

Table identity object.

5. _labels

Declaration

private array $_labels = array();

Description

Labels for the entity.

6. _entityClassName

Declaration

private string $_entityClassName = '';

Description

Entity class name.

7. _entityLanguage

Declaration

private string $_entityLanguage = '';

Description

Entity language code.

Methods

1. __construct

Declaration

public function __construct(
    MagicObject|null $entity = null
)
{
}

Description

Constructor

Parameters

$entity

The entity to load.

2. loadEntityLabel

Declaration

public function loadEntityLabel(
    MagicObject $entity
) : self
{
}

Description

Load data into the object from the given entity.

Parameters

$entity

The entity to load.

Return

self

Returns the current instance for method chaining.

3. addLanguage

Declaration

public function addLanguage(
    string $code,
    object|stdClass|array $reference,
    bool $use = false
) : self
{
}

Description

Add a language to the entity.

Parameters

$code

Language code.

$reference

Reference data for the language.

$use

Flag to indicate whether to use this language immediately.

Return

self

Returns the current instance for method chaining.

4. removeLanguage

Declaration

public function removeLanguage(
    string $code
) : self
{
}

Description

Remove a language from the entity.

Parameters

$code

Language code to remove.

Return

self

Returns the current instance for method chaining.

5. selectLanguage

Declaration

public function selectLanguage(
    string $code
) : self
{
}

Description

Set the current language.

Parameters

$code

Language code to set as current.

Return

self

Returns the current instance for method chaining.

6. propertyList

Declaration

public function propertyList(
    bool $asArrayProps = false
) : array
{
}

Description

Get the list of properties of the entity.

Parameters

$asArrayProps

Flag to determine if result should be returned as an array.

Return

array

List of properties.

7. annotationContent

Declaration

private function annotationContent(
    PicoAnnotationParser $reflexProp,
    PicoGenericObject $parameters,
    string $annotation,
    string $attribute
) : mixed|null
{
}

Description

Get the content of a specific annotation.

Parameters

$reflexProp

Property reflection object.

$parameters

Parameters associated with the property.

$annotation

Annotation name to search for.

$attribute

Attribute name to retrieve.

Return

mixed|null
8. label

Declaration

private function label(
    PicoAnnotationParser $reflexProp,
    PicoGenericObject $parameters,
    string $defaultLabel
) : string
{
}

Description

Define the label for a property.

Parameters

$reflexProp

Property reflection object.

$parameters

Parameters associated with the property.

$defaultLabel

Default label to use if no annotation is found.

Return

string

The defined label.

9. set

Declaration

public function set(
    string $propertyName,
    mixed|null $propertyValue
) : self
{
}

Description

Set a property value.

Parameters

$propertyName

Name of the property to set.

$propertyValue

Value to set for the property.

Return

self

Returns the current instance for method chaining.

10. get

Declaration

public function get(
    string $propertyName
) : mixed|null
{
}

Description

Get a property value.

Parameters

$propertyName

Name of the property to get.

Return

mixed|null

The value of the property or null if not set.

11. __get

Declaration

public function __get(
    string $name
) : mixed
{
}

Description

Magic method to get property values.

Example:

 <?php
 echo $instance->foo;

Parameters

$name

Name of the property to get.

Return

mixed

Value of the property if set, otherwise null.

12. __isset

Declaration

public function __isset(
    string $name
) : bool
{
}

Description

Check if a property is set or not.

Parameters

$name

Name of the property to check.

Return

bool

True if the property is set, false otherwise.

13. __call

Declaration

public function __call(
    string $method,
    array $args
) : mixed|null
{
}

Description

Magic method to handle undefined methods.

This method allows for the dynamic handling of method calls that are not explicitly defined in the class. Specifically, it processes calls to getter methods that start with the prefix "get".

When a method starting with "get" is invoked, this method extracts the property name from the method name and calls the get method to retrieve the corresponding value.

Supported dynamic getter methods:

  • get<PropertyName>: This will call the get method with the property name derived from the method call. For example, calling $obj->getAge() would result in a call to $this->get('age').

    If the method name does not start with "get" or does not correspond to a valid property, this method will return null.

Parameters

$method

Name of the method being called, expected to start with "get".

$args

Arguments passed to the method; typically unused in this context.

Return

mixed|null

The value of the requested property if it exists; otherwise, null.

14. getTableIdentity

Declaration

public function getTableIdentity() : PicoGenericObject
{
}

Description

Get the table identity.

Return

PicoGenericObject

The table identity object.

15. getEntityLanguage

Declaration

public function getEntityLanguage() : string
{
}

Description

Get the entity language code.

Return

string

The entity language code.

16. getEntityClassName

Declaration

public function getEntityClassName() : string
{
}

Description

Get the entity class name.

Return

string

The entity class name.

17. __toString

Declaration

public function __toString() : string
{
}

Description

Converts the object to its string representation.

This method checks if the label language and current language are set. If they are, it returns the JSON-encoded string of the label corresponding to the current language. If not, it returns an empty JSON object.

Return

string

A JSON-encoded string of the label for the current language,

18. getDefaultLabel

Declaration

public function getDefaultLabel() : array
{
}

Description

Get the value of defaultLabel

Return

array

Get default label of the entity

MagicObject\Language\PicoLanguage

Declaration

class PicoLanguage { }

Package

MagicObject\Language

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Language Class

This class represents a language object, allowing for dynamic property management and loading data from arrays or objects.

Methods

1. __construct

Declaration

public function __construct(
    stdClass|array|null $data = null
)
{
}

Description

Constructor

Parameters

$data

Optional data to initialize the object.

2. loadData

Declaration

public function loadData(
    stdClass|array $data
) : self
{
}

Description

Load data into the object.

Parameters

$data

Data to be loaded into the object.

Return

self

Returns the current instance for method chaining.

3. set

Declaration

public function set(
    string $propertyName,
    mixed|null $propertyValue
) : self
{
}

Description

Set a property value.

Parameters

$propertyName

Name of the property to set.

$propertyValue

Value to assign to the property.

Return

self

Returns the current instance for method chaining.

4. get

Declaration

public function get(
    string $propertyName
) : mixed|null
{
}

Description

Get a property value.

Parameters

$propertyName

Name of the property to retrieve.

Return

mixed|null

The value of the property or null if not set.

5. __set

Declaration

public function __set(
    string $name,
    mixed $value
) : void
{
}

Description

Magic method to set property values.

Example:

 <?php
 $instance->foo = 'bar';

Parameters

$name

Name of the property to set.

$value

Value to assign to the property.

Return

void
6. __get

Declaration

public function __get(
    string $name
) : mixed
{
}

Description

Magic method to get property values.

Example:

 <?php
 echo $instance->foo;

Parameters

$name

Name of the property to get.

Return

mixed

The value stored in the property.

7. __isset

Declaration

public function __isset(
    string $name
) : bool
{
}

Description

Check if a property is set.

Parameters

$name

Name of the property to check.

Return

bool

True if the property is set, false otherwise.

8. __unset

Declaration

public function __unset(
    string $name
) : void
{
}

Description

Unset a property value.

Parameters

$name

Name of the property to unset.

Return

void
9. __call

Declaration

public function __call(
    string $method,
    array $params
) : mixed|null
{
}

Description

Magic method called when an undefined method is invoked.

This method provides dynamic handling for method calls that are not explicitly defined in the class. It specifically supports two types of method calls:

  1. Getter Methods:

    • When a method name starts with "get", it retrieves the corresponding property value.
    • For example, calling $obj->getAge() will invoke this method and call $this->get('age').
  2. Equality Check Methods:

    • When a method name starts with "equals", it checks if the provided parameter is equal to the corresponding property value.
    • For example, calling $obj->equalsAge($someValue) will check if $someValue is equal to the value of the age property.

    If the method does not start with "get" or "equals", this method will return null.

Parameters

$method

Name of the method being called. It should start with "get" or "equals".

$params

Parameters passed to the method; for equality checks, it typically contains the value to compare.

Return

mixed|null

The return value of the getter method or the result of the equality check (true or false), or null if the method is not recognized.

MagicObject\Language\PicoMultilanguage

Declaration

class PicoMultilanguage { }

Package

MagicObject\Language

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

PicoMultilanguage Class

This class is designed to handle multi-language support within the application, providing functionalities for managing different language translations.

Methods

1. __construct

Declaration

public function __construct()
{
}

Description

Constructor

Initialize the multilanguage support with default settings or data.

2. loadLanguages

Declaration

public function loadLanguages(
    array $languages
) : self
{
}

Description

Load languages

Parameters

$languages

An array of language codes and their corresponding translations.

Return

self

Returns the current instance for method chaining.

3. getTranslation

Declaration

public function getTranslation(
    string $key,
    string $language
) : string|null
{
}

Description

Get translation

Parameters

$key

The key for the translation to retrieve.

$language

The language code to retrieve the translation for.

Return

string|null

The translation string or null if not found.

MagicObject\Pagination\PicoPagination

Declaration

class PicoPagination { }

Package

MagicObject\Pagination

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for handling pagination functionality.

Properties

1. currentPage

Declaration

private integer $currentPage = 0;

Description

Current page number.

2. pageSize

Declaration

private integer $pageSize = 0;

Description

Number of items per page.

3. offset

Declaration

private integer $offset = 0;

Description

Offset for the current page.

4. orderBy

Declaration

private string $orderBy;

Description

Column name to order by.

5. orderType

Declaration

private string $orderType = '';

Description

Type of order (ASC or DESC).

Methods

1. __construct

Declaration

public function __construct(
    int $pageSize = 20,
    string $orderby = 'orderby',
    string $ordertype = 'ordertype'
)
{
}

Description

Constructor for initializing pagination parameters.

Parameters

$pageSize

Number of items per page (default is 20).

$orderby

Name of the parameter used to retrieve the ordering value (default is 'orderby').

$ordertype

Name of the parameter used to retrieve the order type (ASC or DESC, default is 'ordertype').

2. parseCurrentPage

Declaration

private function parseCurrentPage(
    string $parameterName = 'page'
) : int
{
}

Description

Parse the current page from the request parameters.

Parameters

$parameterName

Name of the parameter used for the page (default is 'page').

Return

int

Current page number, at least 1.

3. createOrder

Declaration

public function createOrder(
    array|null $map = null,
    array|null $filter = null,
    string|null $defaultOrderBy = null
) : string
{
}

Description

Create an ORDER BY clause based on the provided parameters.

Parameters

$map

Mapping of order by columns

$filter

Filter for order by

$defaultOrderBy

Default column name to order by

Return

string

The generated ORDER BY clause

Throws

NullPointerException

if order by is null

4. getOrderBy

Declaration

public function getOrderBy(
    array|null $filter = null,
    string|null $defaultOrderBy = null
) : string|null
{
}

Description

Get the order by column name.

Parameters

$filter

Filter for order by

$defaultOrderBy

Default column name to order by

Return

string|null

The order by column name

5. getOrderType

Declaration

public function getOrderType(
    string|null $defaultOrderType = null
) : string|null
{
}

Description

Get the order type.

Parameters

$defaultOrderType

Default order type (ASC or DESC)

Return

string|null

The order type

6. getCurrentPage

Declaration

public function getCurrentPage() : int
{
}

Description

Get the current page number.

Return

int

The current page number

7. getPageSize

Declaration

public function getPageSize() : int
{
}

Description

Get the page size.

Return

int

The number of items per page

8. getOffset

Declaration

public function getOffset() : int
{
}

Description

Get the offset for the current page.

Return

int

The offset for pagination

9. getPageUrl

Declaration

public static function getPageUrl(
    int $page,
    string $parameterName = 'page',
    string|null $path = null
) : string
{
}

Description

Generate a URL for a specific page.

Parameters

$page

The page number to generate the URL for

$parameterName

The name of the parameter for the page number

$path

The base path for the URL

Return

string

The generated URL

MagicObject\Request\InputCookie

Declaration

class InputCookie extends MagicObject\Request\PicoRequestBase { }

Package

MagicObject\Request

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for handling input from cookies. This class provides functionality to retrieve and parse data from the global $_COOKIE array. It supports options for recursively converting objects and parsing specific types like null and boolean values.

Properties

1. _recursive

Declaration

protected bool $_recursive = false;

Description

Indicates whether to recursively convert all objects.

2. _forceScalar

Declaration

protected bool $_forceScalar = false;

Description

Flag to force input data to be scalar only.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

2. requestCookie

Declaration

public static function requestCookie() : array
{
}

Description

Get the global $_COOKIE variable.

This method is a static wrapper to return the raw cookie data from the $_COOKIE superglobal.

Return

array

The cookie data from the $_COOKIE superglobal.

MagicObject\Request\InputEnv

Declaration

class InputEnv extends MagicObject\Request\PicoRequestBase { }

Package

MagicObject\Request

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for handling input from environment variables.

Properties

1. _forceScalar

Declaration

protected bool $_forceScalar = false;

Description

Flag to force input data to be scalar only.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _recursive

Declaration

protected bool $_recursive = false;

Description

Flag for recursive data processing.

The property name starts with an underscore to prevent child classes from overriding its value.

MagicObject\Request\InputGet

Declaration

class InputGet extends MagicObject\Request\PicoRequestBase { }

Package

MagicObject\Request

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for handling input from HTTP GET requests.

Properties

1. _forceScalar

Declaration

protected bool $_forceScalar = false;

Description

Flag to force input data to be scalar only.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _recursive

Declaration

protected bool $_recursive = false;

Description

Flag for recursive data processing.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

2. requestGet

Declaration

public static function requestGet() : array
{
}

Description

Get the global variable $_GET.

Return

array

The data from the $_GET superglobal.

MagicObject\Request\InputPost

Declaration

class InputPost extends MagicObject\Request\PicoRequestBase { }

Package

MagicObject\Request

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for handling input from HTTP POST requests.

Properties

1. _forceScalar

Declaration

protected bool $_forceScalar = false;

Description

Flag to force input data to be scalar only.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _recursive

Declaration

protected bool $_recursive = false;

Description

Flag for recursive data processing.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

2. requestPost

Declaration

public static function requestPost() : array
{
}

Description

Get the global variable $_POST.

Return

array

The data from the $_POST superglobal.

MagicObject\Request\InputRequest

Declaration

class InputRequest extends MagicObject\Request\PicoRequestBase { }

Package

MagicObject\Request

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for handling input from HTTP requests.

Properties

1. _forceScalar

Declaration

protected bool $_forceScalar = false;

Description

Flag to force input data to be scalar only.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _recursive

Declaration

protected bool $_recursive = false;

Description

Flag for recursive data processing.

The property name starts with an underscore to prevent child classes from overriding its value.

MagicObject\Request\InputServer

Declaration

class InputServer extends MagicObject\Request\PicoRequestBase { }

Package

MagicObject\Request

Authors

  1. Kamshory

Links

  1. https://www.php.net/manual/en/reserved.variables.server.php

Description

Class for handling server input data.

This class provides methods to retrieve various server-related information from the PHP $_SERVER superglobal array, such as request method, server address, and script name.

Available methods:

  • getPhpSelf() returns $_SERVER['PHP_SELF']
  • getGatewayInterface() returns $_SERVER['GATEWAY_INTERFACE']
  • getServerAddr() returns $_SERVER['SERVER_ADDR']
  • getScriptName() returns $_SERVER['SCRIPT_NAME']
  • getServerSoftware() returns $_SERVER['SERVER_SOFTWARE']
  • getServerProtocol() returns $_SERVER['SERVER_PROTOCOL']
  • getRequestMethod() returns $_SERVER['REQUEST_METHOD']
  • getRequestTime() returns $_SERVER['REQUEST_TIME']
  • getRequestTimeFloat() returns $_SERVER['REQUEST_TIME_FLOAT']
  • getQueryString() returns $_SERVER['QUERY_STRING']
  • getDocumentRoot() returns $_SERVER['DOCUMENT_ROOT']
  • getHttps() returns $_SERVER['HTTPS']
  • getRemoteAddr() returns $_SERVER['REMOTE_ADDR']
  • getRemotePort() returns $_SERVER['REMOTE_PORT']
  • getRemoteUser() returns $_SERVER['REMOTE_USER']
  • getRedirectRemoteUser() returns $_SERVER['REDIRECT_REMOTE_USER']
  • getScriptFilename() returns $_SERVER['SCRIPT_FILENAME']
  • getServerAdmin() returns $_SERVER['SERVER_ADMIN']
  • getServerPort() returns $_SERVER['SERVER_PORT']
  • getServerSignature() returns $_SERVER['SERVER_SIGNATURE']
  • getPathTranslated() returns $_SERVER['PATH_TRANSLATED']
  • getRequestUri() returns $_SERVER['REQUEST_URI']
  • getPhpAuthDigest() returns $_SERVER['PHP_AUTH_DIGEST']
  • getPhpAuthUser() returns $_SERVER['PHP_AUTH_USER']
  • getPhpAuthPw() returns $_SERVER['PHP_AUTH_PW']
  • getAuthType() returns $_SERVER['AUTH_TYPE']
  • getPathInfo() returns $_SERVER['PATH_INFO']
  • getOrigPathInfo() returns $_SERVER['ORIG_PATH_INFO']

Properties

1. _forceScalar

Declaration

protected bool $_forceScalar = false;

Description

Flag to force input data to be scalar only.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _recursive

Declaration

protected bool $_recursive = false;

Description

Flag for recursive data processing.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

2. getHeader

Declaration

public function getHeader(
    string $key
) : string|null
{
}

Description

Get a specific request header by key.

Parameters

$key

Header key to retrieve.

Return

string|null

Returns the header value or null if not found.

3. parseLanguages

Declaration

public function parseLanguages(
    string $acceptLanguage
) : array
{
}

Description

Parse the 'Accept-Language' HTTP header.

Parameters

$acceptLanguage

The 'Accept-Language' header value.

Return

array

An associative array of languages with their quality values.

4. userLanguage

Declaration

public function userLanguage(
    bool $general = false
) : string|null
{
}

Description

Get the user's preferred language.

Parameters

$general

Flag to return the general language (default is false).

Return

string|null

Returns the user's preferred language or null if not set.

MagicObject\Request\PicoFilterConstant

Declaration

class PicoFilterConstant { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class containing constants for various filter types.

This class defines a set of filter constants that can be used for sanitizing and validating input data. Each constant represents a specific filter operation.

Constants

const FILTER_DEFAULT = 516;
const FILTER_SANITIZE_NO_DOUBLE_SPACE = 512;
const FILTER_SANITIZE_PASSWORD = 511;
const FILTER_SANITIZE_ALPHA = 510;
const FILTER_SANITIZE_ALPHANUMERIC = 509;
const FILTER_SANITIZE_ALPHANUMERICPUNC = 506;
const FILTER_SANITIZE_NUMBER_UINT = 508;
const FILTER_SANITIZE_NUMBER_INT = 519;
const FILTER_SANITIZE_URL = 518;
const FILTER_SANITIZE_NUMBER_FLOAT = 520;
const FILTER_SANITIZE_STRING_NEW = 513;
const FILTER_SANITIZE_ENCODED = 514;
const FILTER_SANITIZE_STRING_INLINE = 507;
const FILTER_SANITIZE_STRING_BASE64 = 505;
const FILTER_SANITIZE_IP = 504;
const FILTER_SANITIZE_NUMBER_OCTAL = 503;
const FILTER_SANITIZE_NUMBER_HEXADECIMAL = 502;
const FILTER_SANITIZE_COLOR = 501;
const FILTER_SANITIZE_POINT = 500;
const FILTER_SANITIZE_BOOL = 600;
const FILTER_VALIDATE_URL = 273;
const FILTER_VALIDATE_EMAIL = 274;
const FILTER_SANITIZE_EMAIL = 517;
const FILTER_SANITIZE_SPECIAL_CHARS = 515;
const FILTER_SANITIZE_ASCII = 601;

MagicObject\Request\PicoRequest

Declaration

class PicoRequest extends MagicObject\Request\PicoRequestBase { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class for handling HTTP requests.

This class provides methods to manage and retrieve data from various types of HTTP requests (GET, POST, COOKIE, ENV, SERVER).

Constants

const ACTION_DETAIL = "detail";
const ACTION_EDIT = "edit";
const ACTION_ADD = "add";

Properties

1. _forceScalar

Declaration

protected bool $_forceScalar = false;

Description

Flag to force input data to be scalar only.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _recursive

Declaration

protected bool $_recursive = false;

Description

Flag for recursive data processing.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

2. getRequestBody

Declaration

public static function getRequestBody() : string
{
}

Description

Retrieve the raw request body.

Return

string

The raw body of the request.

3. getRequestHeaders

Declaration

public static function getRequestHeaders() : array
{
}

Description

Retrieve all request headers.

Return

array

An associative array of request headers.

4. getRequestHeader

Declaration

public static function getRequestHeader(
    string $key,
    array|null $allHeaders = null
) : string|null
{
}

Description

Retrieve a specific request header by its key.

Parameters

$key

The key of the header to retrieve.

$allHeaders

Optional array of all headers.

Return

string|null

The value of the header, or null if not found.

MagicObject\Request\PicoRequestBase

Declaration

class PicoRequestBase extends stdClass { }

Package

MagicObject\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Base class for handling HTTP requests, including input sanitization, data manipulation, and request type checking (GET, POST, AJAX, etc.).

Constants

const JSON = "JSON";

Properties

1. _classParams

Declaration

private array $_classParams = array();

Description

Class parameters parsed from annotations.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _forceScalar

Declaration

protected bool $_forceScalar = false;

Description

Flag to force input data to be scalar only.

The property name starts with an underscore to prevent child classes from overriding its value.

3. _recursive

Declaration

protected bool $_recursive = false;

Description

Flag for recursive data processing.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

1. __construct

Declaration

public function __construct(
    bool $forceScalar = false
)
{
}

Description

Constructor to initialize the request handler and process class annotations.

Parameters

$forceScalar

Indicates whether to accept only scalar values for data input.

Throws

InvalidAnnotationException

If the annotations are invalid or cannot be parsed.

2. loadData

Declaration

public function loadData(
    mixed $data,
    bool $tolower = false
)
{
}

Description

Load data into the object, transforming keys to camelCase (optional).

Parameters

$data

Data to be loaded (can be an array or object).

$tolower

Flag indicating whether to convert keys to lowercase before loading.

3. set

Declaration

public function set(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Set a property value dynamically on the object using camelCase notation.

Parameters

$propertyName

Name of the property to set.

$propertyValue

Value to assign to the property.

Return

self

Returns the current instance for method chaining.

4. get

Declaration

public function get(
    string $propertyName,
    array|null $params = null
) : mixed|null
{
}

Description

Get a property value dynamically from the object.

Parameters

$propertyName

Name of the property to retrieve.

$params

Optional parameters for filtering the value.

Return

mixed|null
5. value

Declaration

public function value(
    bool $snakeCase = false
) : stdClass
{
}

Description

Get the values of all properties as an object (optionally in snake_case).

Parameters

$snakeCase

Flag to convert property names to snake_case.

Return

stdClass
6. propertyList

Declaration

protected function propertyList(
    bool $reflectSelf = false,
    bool $asArrayProps = false
) : array
{
}

Description

Retrieve a list of properties defined in the class, optionally as an array of property names.

Parameters

$reflectSelf

Flag to indicate whether to include only properties of the current class (not inherited).

$asArrayProps

Flag to return properties as an array of names.

Return

array
7. filterInput

Declaration

public function filterInput(
    int $type,
    string $variableName,
    int $filter = 516,
    bool $escapeSQL = false
) : mixed
{
}

Description

Filter input data from global variables (GET, POST, etc.) according to the specified filter type.

Parameters

$type

The type of input (e.g., INPUT_GET, INPUT_POST).

$variableName

The name of the variable to filter.

$filter

The filter type to apply (e.g., FILTER_SANITIZE_EMAIL).

$escapeSQL

Flag to escape SQL-specific characters.

Return

mixed
8. filterValue

Declaration

public function filterValue(
    mixed $val,
    int $filter = 516,
    bool $escapeSQL = false,
    bool $nullIfEmpty = false,
    bool $requireScalar = false
) : mixed|null
{
}

Description

Filter a value (or nested values) based on the specified filter type and optional flags.

Parameters

$val

The value to be filtered.

$filter

The filter type to apply (e.g., FILTER_SANITIZE_URL).

$escapeSQL

Flag to escape SQL-specific characters.

$nullIfEmpty

Flag to return null if the value is empty.

$requireScalar

Flag to require scalar values.

Return

mixed|null
9. getScalarValue

Declaration

public function getScalarValue(
    mixed $val
) : mixed|null
{
}

Description

Returns the first scalar value from an array or null if no scalar value is found.

This method extracts scalar values from arrays and ignores other types.

Parameters

$val

The value to process. Typically an array or mixed type.

Return

mixed|null

The first scalar value found, or null if no scalar value exists.

10. filterValueSingle

Declaration

public function filterValueSingle(
    mixed $val,
    int $filter = 516,
    bool $escapeSQL = false,
    bool $nullIfEmpty = false
) : mixed
{
}

Description

Filter a single value based on the specified filter type, applying specific sanitization rules.

Parameters

$val

The value to be filtered.

$filter

The filter type to apply (e.g., FILTER_SANITIZE_NUMBER_INT).

$escapeSQL

Flag to escape SQL-specific characters.

$nullIfEmpty

Flag to return null if the value is empty.

Return

mixed
11. addslashes

Declaration

public function addslashes(
    string $input
) : string
{
}

Description

Add escape slashes to a string to protect against SQL injection or special character issues.

Parameters

$input

The input string to escape.

Return

string
12. _getValue

Declaration

public function _getValue(
    stdClass|MagicObject $cfg,
    mixed $input
) : float
{
}

Description

Format and return a numeric value by considering application-specific settings for decimal and thousand separators.

Parameters

$cfg

Configuration object containing separators.

$input

The input value to format.

Return

float
13. isGet

Declaration

public function isGet() : bool
{
}

Description

Check if the request is a GET request.

Return

bool

True if the request method is GET, false otherwise.

14. isPost

Declaration

public function isPost() : bool
{
}

Description

Check if the request is a POST request.

Return

bool

True if the request method is POST, false otherwise.

15. isAjax

Declaration

public function isAjax() : bool
{
}

Description

Check if the request is an AJAX request.

Return

bool

True if the request is an AJAX request, false otherwise.

16. getHttpMethod

Declaration

public function getHttpMethod() : string
{
}

Description

Retrieve the HTTP method used for the current request.

Return

string

The HTTP method (e.g., GET, POST).

17. getUserAgent

Declaration

public function getUserAgent() : string
{
}

Description

Retrieve the user agent string from the request headers.

Return

string

The user agent string.

18. getClientIp

Declaration

public function getClientIp() : string
{
}

Description

Retrieve the client's IP address from the request headers.

Return

string

The client's IP address.

19. __call

Declaration

public function __call(
    string $method,
    array $params
) : mixed|null
{
}

Description

Magic method to handle dynamic method calls.

This method is invoked when an undefined method is called on the object. It supports various dynamic operations based on method names, allowing for flexible interaction with object properties.

Supported method patterns:

  1. Countable Check:

    • countable<propertyName>(): Checks if the specified property is set and is an array.
      $instance->countableItems(); // Returns true if $items is an array.
  2. Existence Check:

    • isset<propertyName>(): Checks if the specified property is set.
      $instance->issetUsername(); // Returns true if $username is set.
  3. Boolean Check:

    • is<propertyName>(): Returns true if the specified property is set and evaluates to true (1 or 'true').
      $instance->isActive(); // Returns true if $active is true or 1.
  4. Getter Method:

    • get<propertyName>(): Retrieves the value of the specified property using the get() method.
      $value = $instance->getAge(); // Returns the value of $age.
  5. Setter Method:

    • set<propertyName>($value): Sets the specified property to the provided value.
      $instance->setUsername('newUsername'); // Sets $username to 'newUsername'.
  6. Equality Check:

    • equals<propertyName>($value): Compares the specified value with the property and returns true if they are equal.
      $isEqual = $instance->equalsUsername('newUsername'); // Returns true if $username is 'newUsername'.
  7. Checkbox Handling:

    • checkbox<propertyName>($value): Sets the property to the provided value if it is not already set.
      $instance->checkboxTermsAccepted(true); // Sets $termsAccepted to true if it wasn't already.
  8. Filter Application:

    • filter<propertyName>($filter): Applies a filter to the specified property value if it is set.
      $instance->filterEmail('sanitize'); // Applies 'sanitize' filter to $email if set.
  9. Selected Attribute Creation:

    • createSelected<propertyName>($value): Returns ' selected="selected"' if the property value matches the provided value.
      $selected = $instance->createSelectedCountry('US'); // Returns ' selected="selected"' if $country is 'US'.
  10. Checked Attribute Creation:

    • createChecked<propertyName>($value): Returns ' checked="checked"' if the property value matches the provided value.
      $checked = $instance->createCheckedNewsletter(true); // Returns ' checked="checked"' if $newsletter is true.
  11. Unset Method:

    • unset<propertyName>(): Unsets specified property value.
      $instance->unsetTags(); // Unsets the property 'tags'.

    If the method does not match any of the patterns above, the method will return null.

Parameters

$method

Name of the method being called.

$params

Parameters passed to the method.

Return

mixed|null

The result of the method call, or null if the method is not recognized.

20. applyFilter

Declaration

private function applyFilter(
    string|null $value,
    string $filterType
) : string|boolean|null
{
}

Description

Apply a filter to the given value based on the specified filter type.

This method sanitizes the input value according to the filter type. If the filter type is FILTER_SANITIZE_SPECIAL_CHARS, it converts special characters to HTML entities. If the filter type is FILTER_SANITIZE_BOOL, it evaluates the value as a boolean. Otherwise, it returns the value unchanged.

Parameters

$value

The value to be filtered.

$filterType

The type of filter to apply.

Return

string|boolean|null

The filtered value, a boolean for FILTER_SANITIZE_BOOL, or null if the value is not set.

21. isSnake

Declaration

private function isSnake() : bool
{
}

Description

Check if the JSON naming strategy is snake case.

Return

bool

True if the naming strategy is snake case, false otherwise.

22. isCamel

Declaration

protected function isCamel() : bool
{
}

Description

Check if the JSON naming strategy is set to camel case.

This method returns true if the JSON naming strategy is not snake case, indicating that camel case is used instead.

Return

bool

True if the naming strategy is camel case, false otherwise.

23. isPretty

Declaration

private function isPretty() : bool
{
}

Description

Check if the JSON output should be prettified.

This method determines if the prettification option is enabled in the JSON configuration, indicating whether the output should be formatted for readability.

Return

bool

True if the prettify option is enabled, false otherwise.

24. isEmpty

Declaration

public function isEmpty() : bool
{
}

Description

Check if the request is empty.

This method checks whether the current request has no values set, indicating that it is considered empty.

Return

bool

True if the request is empty, false otherwise.

25. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the object to a JSON string representation.

This method serializes the object to JSON format, with options for pretty printing based on the configuration. It uses the appropriate naming strategy for properties as specified in the class parameters.

Return

string

The JSON string representation of the object.

MagicObject\Response\Generated\JSONSelectOption

Declaration

class JSONSelectOption { }

Package

MagicObject\Response\Generated

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class JSONSelectOption

This class fetches data from a database and prepares it for use in JSON select options.

Properties

1. data

Declaration

private $data = array();

Description

@var array

Methods

1. __construct

Declaration

public function __construct(
    PicoDatabase $database,
    PicoDatabaseQueryBuilder $query,
    mixed $defaultValue
)
{
}

Description

Constructor

Initializes the JSONSelectOption with data fetched from the database.

Parameters

$database

Database connection

$query

Query builder for fetching data

$defaultValue

Default value to mark as selected

2. updateData

Declaration

private function updateData(
    array|null $rows,
    mixed $defaultValue
)
{
}

Description

Update data with selected value.

Marks the row with the specified default value as selected.

Parameters

$rows

Fetched rows from the database

$defaultValue

Default value to mark as selected

3. getData

Declaration

public function getData() : array
{
}

Description

Get the value of data

Return

array

Data with selection information

4. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the data to JSON format

Return

string

JSON representation of the data

MagicObject\Response\Generated\PicoSelectOption

Declaration

class PicoSelectOption { }

Package

MagicObject\Response\Generated

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoSelectOption

This class generates HTML <option> elements based on data from a MagicObject entity.

Properties

1. object

Declaration

private MagicObject $object;

Description

Entity object

2. map

Declaration

private array $map = array();

Description

Mapping of value and label fields

3. value

Declaration

private mixed $value;

Description

Selected value

4. attributes

Declaration

private array $attributes = array();

Description

Additional attributes for options

5. rows

Declaration

private array $rows = array();

Description

Rows for generating options

6. sortable

Declaration

private PicoSortable $sortable;

Description

Sortable options

Methods

1. __construct

Declaration

public function __construct(
    MagicObject $object,
    array $map,
    mixed $value,
    array|null $attributes = null,
    PicoSortable|null $sortable = null
)
{
}

Description

Constructor

Initializes the PicoSelectOption with the provided parameters and fetches active options.

Parameters

$object

Entity to fetch data from

$map

Mapping for value and label keys

$value

Selected value

$attributes

Additional attributes for the options

$sortable

Sortable options for fetching

2. createAttributes

Declaration

private function createAttributes(
    MagicObject $row,
    string $attr,
    string $value
) : array
{
}

Description

Create attributes for an option element.

Parameters

$row

Entity representing a row.

$attr

Attribute name for the option.

$value

Option value.

Return

array

Attributes for the option element.

3. findAllActive

Declaration

private function findAllActive() : void
{
}

Description

Find all active options from the database

Return

void
4. attributeToString

Declaration

private function attributeToString(
    array $array
) : string
{
}

Description

Convert an array of attributes to an HTML attributes string.

Parameters

$array

Attributes to convert.

Return

string

String representation of HTML attributes.

5. __toString

Declaration

public function __toString() : string
{
}

Description

Convert the options to HTML <option> elements.

Return

string

HTML string of <option> elements.

MagicObject\Response\PicoResponse

Declaration

class PicoResponse { }

Package

MagicObject\Response

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoResponse Handles sending HTTP responses with various content types and status codes.

Constants

const APPLICATION_JSON = "application/json";

Methods

1. sendJSON

Declaration

public static function sendJSON(
    mixed $data,
    bool $prettify = false,
    array|null $headers = null,
    int $httpStatusCode = 200
) : void
{
}

Description

Send a JSON response to the client.

Parameters

$data

Data to send to the client

$prettify

Flag to prettify JSON

$headers

Response headers

$httpStatusCode

HTTP status code (default: 200)

Return

void
2. sendResponse

Declaration

public static function sendResponse(
    string|null $body,
    string|null $contentType = null,
    array|null $headers = null,
    int $httpStatusCode = 200,
    bool $async = false
) : void
{
}

Description

Send the response headers and body to the client.

Parameters

$body

Response body

$contentType

Content type

$headers

Response headers

$httpStatusCode

HTTP status code (default: 200)

$async

Send response asynchronously

Return

void
3. sendResponseJSON

Declaration

public static function sendResponseJSON(
    stdClass|object|array|string|null $body,
    array|null $headers = null,
    int $httpStatusCode = 200,
    bool $async = false
) : void
{
}

Description

Send response as JSON to the client.

Parameters

$body

Response body

$headers

Response headers

$httpStatusCode

HTTP status code (default: 200)

$async

Send response asynchronously

Return

void
4. sendHeaders

Declaration

public static function sendHeaders(
    array $headers
) : void
{
}

Description

Send response headers to the client.

Parameters

$headers

Response headers

Return

void
5. sendBody

Declaration

public static function sendBody(
    string|null $body,
    bool $async = false
) : void
{
}

Description

Send response body to the client.

Parameters

$body

Response body

$async

Send response asynchronously

Return

void
6. getDefaultContentType

Declaration

public static function getDefaultContentType(
    string|null $contentType
) : string
{
}

Description

Get default content type based on the provided content type.

Parameters

$contentType

Content type

Return

string

Fixed content type

7. getDefaultHeaders

Declaration

public static function getDefaultHeaders(
    array|null $headers,
    string|null $contentType,
    int $contentLength = 0
) : array
{
}

Description

Get default response headers.

Parameters

$headers

Response headers

$contentType

Content type

$contentLength

Content length

Return

array

Fixed response headers

8. sendHttpStatus

Declaration

public static function sendHttpStatus(
    int $code = 0,
    string|null $text = null
) : int
{
}

Description

Send HTTP status code.

Parameters

$code

HTTP status code

$text

HTTP status text

Return

int

The HTTP status code sent

9. getHttpResponseCode

Declaration

public static function getHttpResponseCode(
    int $code
) : string|null
{
}

Description

Get HTTP response code text.

Parameters

$code

HTTP status code

Return

string|null

The HTTP status text or null if not found

10. redirectToItself

Declaration

public static function redirectToItself() : void
{
}

Description

Redirect the browser to the current URL. WARNING: Use this only if there is a POST input that will control the process to prevent an endless loop that could damage the server.

Return

void

MagicObject\Secret\PicoSecret

Declaration

class PicoSecret { }

Package

MagicObject\Secret

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Default secret key WARNING: Use your own key instead of using default key

Constants

const RANDOM_KEY_1 = "68e656b251e67e8358bef8483ab0d51c";
const RANDOM_KEY_2 = "6619f3e7a1a9f0e75838d41ff368f728";

MagicObject\Session\PicoSession

Declaration

class PicoSession { }

Package

MagicObject\Session

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoSession This class manages session handling, providing methods to configure and manipulate sessions.

The class provides an interface for session management, including handling session creation, destruction, configuration, and the ability to store/retrieve session data.

Constants

const SESSION_STARTED = true;
const SESSION_NOT_STARTED = false;
const SAME_SITE_LAX = "Lax";
const SAME_SITE_STRICT = "Strict";
const SAME_SITE_NONE = "None";

Properties

1. _sessionState

Declaration

private boolean $_sessionState = false;

Description

The state of the session.

The property name starts with an underscore to prevent child classes from overriding its value.

2. _instance

Declaration

private self $_instance;

Description

The instance of the object.

The property name starts with an underscore to prevent child classes from overriding its value.

Methods

1. __construct

Declaration

public function __construct(
    SecretObject|null $sessConf = null
)
{
}

Description

Constructor to initialize session configuration.

This constructor accepts a session configuration object and applies settings such as session name, max lifetime, and save handler (Redis or file system).

Parameters

$sessConf

Configuration for the session.

2. getInstance

Declaration

public static function getInstance(
    string|null $name = null,
    int $maxLifeTime = 0
) : self
{
}

Description

Returns the instance of PicoSession. The session is automatically initialized if it wasn't already.

This method ensures that only one instance of PicoSession is created (Singleton pattern).

Parameters

$name

Session name.

$maxLifeTime

Maximum lifetime of the session.

Return

self

The instance of PicoSession.

3. startSession

Declaration

public function startSession() : bool
{
}

Description

(Re)starts the session.

This method starts a session if it hasn't been started already.

Return

bool

True if the session has been initialized, false otherwise.

4. isSessionStarted

Declaration

public function isSessionStarted() : bool
{
}

Description

Checks if the session has been started.

This method checks whether the current session has been started.

Return

bool

True if the session has started, false otherwise.

5. __set

Declaration

public function __set(
    string $name,
    mixed $value
) : void
{
}

Description

Stores data in the session.

Example:

 <?php
 $sessions->foo = 'bar';

This magic method stores data in the PHP session.

Parameters

$name

Name of the data.

$value

The data to store.

Return

void
6. __get

Declaration

public function __get(
    string $name
) : mixed
{
}

Description

Retrieves data from the session.

Example:

 <?php
 echo $sessions->foo;

This magic method retrieves data from the PHP session.

Parameters

$name

Name of the data to retrieve.

Return

mixed

The data stored in session, or null if not set.

7. __isset

Declaration

public function __isset(
    string $name
) : bool
{
}

Description

Checks if a value is set in the session.

This magic method checks whether a value is set in the session.

Parameters

$name

Name of the data to check.

Return

bool

True if the data is set, false otherwise.

8. __unset

Declaration

public function __unset(
    string $name
) : void
{
}

Description

Unsets a value in the session.

This magic method unsets data in the session.

Parameters

$name

Name of the data to unset.

Return

void
9. destroy

Declaration

public function destroy() : bool
{
}

Description

Destroys the current session.

This method destroys the session and clears all session data.

Return

bool

true if the session has been deleted, else false.

10. setSessionCookieParams

Declaration

public function setSessionCookieParams(
    int $maxlifetime,
    string $path,
    string $domain,
    bool $secure,
    bool $httponly,
    string $samesite = 'Strict'
) : self
{
}

Description

Sets the session cookie parameters, including lifetime, path, domain, security attributes, and SameSite settings.

This method configures the session cookie parameters such as maximum lifetime, path, domain, and security settings like whether the cookie should be accessible only over HTTPS or only via HTTP. It also sets the SameSite attribute for compatibility with different browsers and PHP versions.

Parameters

$maxlifetime

Maximum lifetime of the session cookie in seconds.

$path

The path where the cookie will be available on the server.

$domain

The domain to which the cookie is available.

$secure

Indicates if the cookie should only be transmitted over a secure HTTPS connection.

$httponly

Indicates if the cookie should be accessible only through the HTTP protocol.

$samesite

The SameSite attribute of the cookie (Lax, Strict, None). Default is 'Strict'.

Return

self

Returns the current instance for method chaining.

11. setSessionCookieSameSite

Declaration

public function setSessionCookieSameSite(
    string $name,
    string $value,
    int $expire,
    string $path,
    string $domain,
    bool $secure,
    bool $httponly,
    string $samesite = 'Strict'
) : self
{
}

Description

Sets a cookie with the SameSite attribute, supporting both older and newer PHP versions.

This method sets a cookie with a specified SameSite attribute, ensuring compatibility with both PHP versions prior to and after PHP 7.3. It supports cookies with the 'Lax', 'Strict', or 'None' SameSite attributes.

Parameters

$name

The name of the cookie.

$value

The value of the cookie.

$expire

The expiration time of the cookie as a Unix timestamp.

$path

The path on the server where the cookie is available.

$domain

The domain to which the cookie is available.

$secure

Indicates if the cookie should only be transmitted over a secure HTTPS connection.

$httponly

Indicates if the cookie is accessible only through the HTTP protocol.

$samesite

The SameSite attribute of the cookie (Lax, Strict, None). Default is 'Strict'.

Return

self

Returns the current instance for method chaining.

12. setSessionName

Declaration

public function setSessionName(
    string $name
) : self
{
}

Description

Sets the session name.

This method sets the session name for the current session.

Parameters

$name

The name of the session.

Return

self

Returns the current instance for method chaining.

13. setSessionSavePath

Declaration

public function setSessionSavePath(
    string $path
) : string|false
{
}

Description

Sets the session save path.

This method sets the path where session files will be stored.

Parameters

$path

The session save path.

Return

string|false

The session save path on success, false on failure.

14. setSessionMaxLifeTime

Declaration

public function setSessionMaxLifeTime(
    int $lifeTime
) : self
{
}

Description

Sets the maximum lifetime for the session.

This method sets the maximum lifetime of the session, affecting both garbage collection and cookie expiration.

Parameters

$lifeTime

Maximum lifetime for the session in seconds.

Return

self

Returns the current instance for method chaining.

15. saveToRedis

Declaration

public function saveToRedis(
    string $host,
    int $port,
    string $auth
) : self
{
}

Description

Saves the session to Redis.

This method configures the session to be stored in Redis.

Parameters

$host

Redis host.

$port

Redis port.

$auth

Redis authentication.

Return

self

Returns the current instance for method chaining.

16. saveToFiles

Declaration

public function saveToFiles(
    string $path
) : self
{
}

Description

Saves the session to files.

This method configures the session to be stored in files.

Parameters

$path

The directory where session files will be stored.

Return

self

Returns the current instance for method chaining.

17. getSessionId

Declaration

public function getSessionId() : string
{
}

Description

Retrieves the current session ID.

This method retrieves the current session ID, if any.

Return

string

The current session ID.

18. setSessionId

Declaration

public function setSessionId(
    string $id
) : self
{
}

Description

Sets a new session ID.

This method sets a new session ID for the current session.

Parameters

$id

The new session ID.

Return

self

Returns the current instance for method chaining.

19. __toString

Declaration

public function __toString() : string
{
}

Description

Converts the session data to a string representation.

This method returns the session data as a JSON-encoded string, which can be useful for debugging or logging the contents of the session. It encodes the global $_SESSION array into a JSON string.

Return

string

The JSON-encoded string representation of the session data.

MagicObject\Util\AttrUtil

Declaration

class AttrUtil { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class AttrUtil

A utility class for generating HTML attribute strings based on comparisons between two parameters. This is useful for dynamically setting attributes like selected and checked in HTML forms.

This class is intended to be used statically and cannot be instantiated.

Methods

2. selected

Declaration

public static function selected(
    mixed $param1,
    mixed $param2
) : string
{
}

Description

Returns ' selected="selected"' if $param1 equals $param2.

This method is useful for setting the selected attribute on option elements in a dropdown when the current value matches the value of the option.

Example:

 <?php
 echo AttrUtil::selected($currentValue, $optionValue);
 // Outputs: selected="selected" if they match

Parameters

$param1

The first parameter to compare.

$param2

The second parameter to compare.

Return

string

The attribute string if matched, empty string otherwise.

3. checked

Declaration

public static function checked(
    mixed $param1,
    mixed $param2
) : string
{
}

Description

Returns ' checked="checked"' if $param1 equals $param2.

This method is useful for setting the checked attribute on checkbox or radio button elements when the current value matches the value of the input.

Example:

 <?php
 echo AttrUtil::checked($currentValue, $inputValue);
 // Outputs: checked="checked" if they match

Parameters

$param1

The first parameter to compare.

$param2

The second parameter to compare.

Return

string

The attribute string if matched, empty string otherwise.

MagicObject\Util\ClassUtil\ExtendedReflectionClass

Declaration

class ExtendedReflectionClass extends ReflectionClass implements Reflector { }

Package

MagicObject\Util\ClassUtil

Description

The MIT License (MIT)

Copyright (c) Ozgur (Ozzy) Giritli ozgur@zeronights.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Properties

1. useStatements

Declaration

protected array $useStatements = array();

Description

Array of use statements for the class.

2. useStatementsParsed

Declaration

protected bool $useStatementsParsed = false;

Description

Flag indicating whether use statements have been parsed.

Methods

1. parseUseStatements

Declaration

protected function parseUseStatements() : array
{
}

Description

Parses the class file and retrieves use statements from the current namespace.

This method reads the source of the class file, tokenizes it, and extracts the use statements. If the use statements have already been parsed, it returns the cached results.

Return

array

An array of use statements.

Throws

InvalidClassException

If the class is not user-defined.

2. readFileSource

Declaration

private function readFileSource() : string
{
}

Description

Reads the source code of the class file up to the line where the class is defined.

Return

string

The source code of the class file up to the class definition.

3. tokenizeSource

Declaration

private function tokenizeSource(
    string $source
) : array
{
}

Description

Tokenizes the source code and extracts use statements.

This method parses the tokens in the source code to identify use statements and their aliases, returning an array of these statements.

Parameters

$source

The source code to be tokenized.

Return

array

An array of use statements, including aliases.

4. getUseStatements

Declaration

public function getUseStatements() : array
{
}

Description

Returns the array of use statements for the class.

Return

array

An array of use statements for the class.

5. baseName

Declaration

private function baseName(
    string $className
) : string
{
}

Description

Extracts the base name of a class from its fully qualified name.

Parameters

$className

The fully qualified class name.

Return

string

The base name of the class (i.e., the class name without namespace).

6. hasUseStatement

Declaration

public function hasUseStatement(
    string $class
) : bool
{
}

Description

Checks if the class has a specific use statement or alias.

Parameters

$class

The name of the class to check.

Return

bool

True if the class or its alias is found in the use statements, false otherwise.

MagicObject\Util\ClassUtil\PicoAnnotationParser

Declaration

class PicoAnnotationParser { }

Package

MagicObject\Util\ClassUtil

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Annotation parser for handling and processing annotations in PHP classes.

This class is designed to read, parse, and manage annotations present in the doc comments of classes, methods, and properties. It provides functionalities to retrieve annotations as arrays or objects, handle key-value pairs from query strings, and validate input parameters.

The PicoAnnotationParser is particularly useful in frameworks or libraries that rely on annotations for configuration, routing, or metadata purposes.

Constants

const METHOD = "method";
const PROPERTY = "property";

Properties

1. rawDocBlock

Declaration

private string $rawDocBlock;

Description

Raw docblock

2. parameters

Declaration

private array $parameters;

Description

Parameters

3. keyPattern

Declaration

private string $keyPattern = '[A-z0-9\\_\\-]+';

Description

Key pattern

4. endPattern

Declaration

private string $endPattern = '[ ]*(?:@| | )';

Description

End pattern

5. parsedAll

Declaration

private bool $parsedAll = false;

Description

Parsed state

6. reflection

Declaration

private ReflectionClass $reflection;

Description

Reflection object

Methods

1. __construct

Declaration

public function __construct(
    mixed
)
{
}

Description

Constructor

Parameters

mixed

...$args

Throws

ZeroArgumentException|InvalidParameterException
2. getProperties

Declaration

public function getProperties() : ReflectionProperty[]
{
}

Description

Retrieves all properties of the reflected class or method.

Return

ReflectionProperty[]

An array of ReflectionProperty objects.

3. isNullOrEmpty

Declaration

private function isNullOrEmpty(
    string $value
) : bool
{
}

Description

Checks if the given value is null or empty.

Parameters

$value

The value to check.

Return

bool

True if the value is null or empty, otherwise false.

4. parseSingle

Declaration

private function parseSingle(
    string $key
) : array|null
{
}

Description

Parses a single annotation based on the provided key.

Parameters

$key

The annotation key to parse.

Return

array|null

The parsed value(s) of the annotation or null if not found.

5. parse

Declaration

private function parse() : void
{
}

Description

Parses all annotations found in the raw docblock.

This method should not be called directly; use getParameters() to access parsed parameters instead.

Return

void
6. fixDuplication

Declaration

private function fixDuplication() : void
{
}

Description

Fixes duplicated annotations by keeping only the last occurrence.

This method is called during the parsing process.

Return

void
7. getVariableDeclarations

Declaration

public function getVariableDeclarations(
    string $name
) : string[]
{
}

Description

Retrieves declared variables from a specified annotation.

Parameters

$name

The name of the annotation to retrieve variables from.

Return

string[]

An array of declared variables.

8. parseVariableDeclaration

Declaration

private function parseVariableDeclaration(
    mixed $declaration,
    string $name
) : string[]
{
}

Description

Parses a variable declaration from an annotation.

Parameters

$declaration

The raw declaration string.

$name

The name of the annotation for error context.

Return

string[]

An array containing 'type' and 'name'.

Throws

InvalidArgumentException

if the declaration is not a string or is empty.

9. parseValue

Declaration

private function parseValue(
    string $originalValue
) : mixed
{
}

Description

Parse value

Parameters

$originalValue

Original value

Return

mixed
10. getParameters

Declaration

public function getParameters() : array
{
}

Description

Retrieves all parameters from the parsed annotations.

If the annotations have not been parsed yet, this method will trigger parsing.

Return

array

An associative array of parsed annotation parameters.

11. getParametersAsObject

Declaration

public function getParametersAsObject() : PicoGenericObject
{
}

Description

Retrieves all parameters as an object of type PicoGenericObject.

If the annotations have not been parsed yet, this method will trigger parsing.

Return

PicoGenericObject

An object containing the parsed annotation parameters.

12. getParameter

Declaration

public function getParameter(
    string $key
) : mixed
{
}

Description

Retrieves a specific parameter by its key.

Parameters

$key

The key of the parameter to retrieve.

Return

mixed

The value of the specified parameter or null if not found.

13. getFirstParameter

Declaration

public function getFirstParameter(
    string $key
) : string|null
{
}

Description

Get the first parameter for a given key from the parsed annotations.

This method retrieves the first value associated with the specified key. If the parameter does not exist or is null, it returns null. If the parameter is an array, it returns the first string element. Otherwise, it returns the value directly.

Parameters

$key

The key for which to retrieve the first parameter.

Return

string|null

The first parameter value, or null if not found.

14. combineAndMerge

Declaration

private function combineAndMerge(
    array $matches,
    array $pair
) : array
{
}

Description

Combine and merge two arrays, where the first array contains keys and the second contains values.

This method checks if both arrays are set and are of the correct type. It combines them into a new associative array and returns the merged result.

Parameters

$matches

An array of matched keys and values.

$pair

An associative array to merge with.

Return

array

The merged array containing keys and values from both input arrays.

15. parseKeyValue

Declaration

public function parseKeyValue(
    string $parametersString
) : string[]
{
}

Description

Parse key-value pairs from parameters string.

This method extracts key-value pairs from parameters string, which may contain attributes with or without quotes. Numeric attributes will have an underscore prefix. Throws an exception if the input is invalid.

Parameters

$parametersString

The parameters string to parse.

Return

string[]

An associative array of parsed key-value pairs.

Throws

InvalidAnnotationException

If the annotations are invalid or cannot be parsed.

16. matchArgs

Declaration

private function matchArgs(
    array $keys,
    string $val
) : bool
{
}

Description

Check if the provided value matches the expected criteria.

This method checks if the given value does not contain an equals sign, quotes, and is not present in the provided keys array.

Parameters

$keys

The array of valid keys.

$val

The value to check.

Return

bool

True if the value matches the criteria, otherwise false.

17. parseKeyValueAsObject

Declaration

public function parseKeyValueAsObject(
    string $parametersString
) : PicoGenericObject
{
}

Description

Parse parameters from parameters string and return them as a PicoGenericObject.

This method transforms the key-value pairs parsed from the parameters string into an instance of PicoGenericObject. All numeric attributes will be prefixed with an underscore.

Parameters

$parametersString

The parameters string to parse.

Return

PicoGenericObject

An object containing the parsed key-value pairs.

Throws

InvalidAnnotationException

If the annotations are invalid or cannot be parsed.

MagicObject\Util\ClassUtil\PicoEmptyParameter

Declaration

class PicoEmptyParameter { }

Package

MagicObject\Util\ClassUtil

Description

Class PicoEmptyParameter

This class serves as a placeholder for future implementation or to represent an empty parameter in the context of parameter handling within the MagicObject framework. It may be used for type hinting or as a marker in method signatures where no parameters are required.

MagicObject\Util\ClassUtil\PicoObjectParser

Declaration

class PicoObjectParser { }

Package

MagicObject\Util\ClassUtil

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoObjectParser

This class provides methods to parse various data formats (YAML, JSON, etc.) into instances of MagicObject. It supports recursive parsing for nested objects and arrays, allowing for flexible data structure handling.

Methods

1. parseMagicObject

Declaration

private static function parseMagicObject(
    MagicObject $data
) : MagicObject
{
}

Description

Parse a MagicObject from a given data structure.

This method converts a MagicObject instance into a new MagicObject by mapping scalar values and recursively parsing nested objects.

Parameters

$data

The MagicObject instance to parse.

Return

MagicObject

The parsed MagicObject.

2. parseObject

Declaration

private static function parseObject(
    stdClass|array $data
) : MagicObject
{
}

Description

Parse an object or associative array into a MagicObject.

This method iterates over the given data structure, converting keys to camel case and mapping scalar values directly while handling nested structures recursively.

Parameters

$data

The data to parse, which can be an object or an associative array.

Return

MagicObject

The resulting MagicObject after parsing.

3. hasStringKeys

Declaration

private static function hasStringKeys(
    array $array
) : bool
{
}

Description

Check if the given array has string keys, indicating it is associative.

Parameters

$array

The array to check.

Return

bool

True if the array has string keys, false otherwise.

4. parseRecursiveObject

Declaration

public static function parseRecursiveObject(
    mixed $data
) : mixed
{
}

Description

Recursively parse data into a MagicObject.

This method handles various data types, converting them into a MagicObject or returning them as-is when appropriate.

Parameters

$data

The data to parse, which may be a MagicObject, array, object, or scalar.

Return

mixed

The parsed MagicObject or original data.

5. updateObject

Declaration

private static function updateObject(
    MagicObject $obj,
    string $key,
    mixed $val
) : MagicObject
{
}

Description

Update a MagicObject with a key-value pair.

This method determines if the value is an object or array and updates the MagicObject accordingly, using recursion as necessary.

Parameters

$obj

The MagicObject to update.

$key

The property name to set.

$val

The property value to assign.

Return

MagicObject

The updated MagicObject.

6. isObject

Declaration

private static function isObject(
    mixed $value
) : bool
{
}

Description

Check if the given value is an object.

Parameters

$value

The value to check.

Return

bool

True if the value is an object, false otherwise.

7. parseRecursiveArray

Declaration

public static function parseRecursiveArray(
    array $data
) : array
{
}

Description

Recursively parse an array into a MagicObject.

This method processes each element of the array, converting nested objects or arrays into MagicObject instances as needed.

Parameters

$data

The array to parse.

Return

array

An array of parsed MagicObject instances or original values.

8. parseYamlRecursive

Declaration

public static function parseYamlRecursive(
    string $yamlString
) : MagicObject|null
{
}

Description

Parse a YAML string recursively into a MagicObject.

This method converts a YAML string into a structured MagicObject by first parsing the string into an array or object, then processing it.

Parameters

$yamlString

The YAML string to parse.

Return

MagicObject|null

The resulting MagicObject or null if parsing fails.

9. parseJsonRecursive

Declaration

public static function parseJsonRecursive(
    mixed $data
) : MagicObject|null
{
}

Description

Parse JSON data recursively into a MagicObject.

This method takes JSON-encoded strings or data structures and converts them into MagicObject instances, handling various data types.

Parameters

$data

The JSON data to parse, which can be a string, array, or object.

Return

MagicObject|null

The resulting MagicObject or null if the data is not valid.

10. parseString

Declaration

public static function parseString(
    string $data
) : mixed
{
}

Description

Parse a string representation of a value into its appropriate type.

This method converts specific string values ('null', 'true', 'false') into their respective PHP types while returning all other strings as-is.

Parameters

$data

The string data to parse.

Return

mixed

The parsed value, which may be null, boolean, or string.

MagicObject\Util\ClassUtil\PicoSecretParser

Declaration

class PicoSecretParser { }

Package

MagicObject\Util\ClassUtil

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoSecretParser

This class provides methods to parse various data formats (YAML, JSON, etc.) into instances of SecretObject. It supports recursive parsing for nested objects and arrays, allowing for flexible handling of secret-related data structures.

Methods

2. parseSecretObject

Declaration

private static function parseSecretObject(
    SecretObject $data
) : SecretObject
{
}

Description

Parse a SecretObject from a given data structure.

This method converts a SecretObject instance into a new SecretObject by mapping scalar values and recursively parsing nested objects.

Parameters

$data

The SecretObject instance to parse.

Return

SecretObject

The parsed SecretObject.

3. parseObject

Declaration

private static function parseObject(
    stdClass|array $data
) : SecretObject
{
}

Description

Parse an object or associative array into a SecretObject.

This method iterates over the given data structure, converting keys to camel case and mapping scalar values directly while handling nested structures recursively.

Parameters

$data

The data to parse, which can be an object or an associative array.

Return

SecretObject

The resulting SecretObject after parsing.

4. hasStringKeys

Declaration

private static function hasStringKeys(
    array $array
) : bool
{
}

Description

Check if the input is an associative array.

This method determines whether the provided array has string keys, indicating it is associative.

Parameters

$array

The array to check.

Return

bool

True if the array has string keys, false otherwise.

5. parseRecursiveObject

Declaration

public static function parseRecursiveObject(
    mixed $data
) : mixed
{
}

Description

Recursively parse data into a SecretObject.

This method handles various data types, converting them into a SecretObject or returning them as-is when appropriate.

Parameters

$data

The data to parse, which may be a SecretObject, array, object, or scalar.

Return

mixed

The parsed SecretObject or original data.

6. updateObject

Declaration

private static function updateObject(
    SecretObject $obj,
    string $key,
    mixed $val
) : SecretObject
{
}

Description

Update a SecretObject with a key-value pair.

This method determines if the value is an object or array and updates the SecretObject accordingly, using recursion as necessary.

Parameters

$obj

The SecretObject to update.

$key

The property name to set.

$val

The property value to assign.

Return

SecretObject

The updated SecretObject.

7. isObject

Declaration

private static function isObject(
    mixed $value
) : bool
{
}

Description

Check if the given value is an object.

Parameters

$value

The value to check.

Return

bool

True if the value is an object, false otherwise.

8. parseRecursiveArray

Declaration

public static function parseRecursiveArray(
    array $data
) : array
{
}

Description

Recursively parse an array into a SecretObject.

This method processes each element of the array, converting nested objects or arrays into SecretObject instances as needed.

Parameters

$data

The array to parse.

Return

array

An array of parsed SecretObject instances or original values.

9. parseYamlRecursive

Declaration

public static function parseYamlRecursive(
    string $yamlString
) : SecretObject|null
{
}

Description

Parse a YAML string recursively into a SecretObject.

This method converts a YAML string into a structured SecretObject by first parsing the string into an array or object, then processing it.

Parameters

$yamlString

The YAML string to parse.

Return

SecretObject|null

The resulting SecretObject or null if parsing fails.

10. parseJsonRecursive

Declaration

public static function parseJsonRecursive(
    string $jsonString
) : SecretObject|null
{
}

Description

Parse JSON data recursively into a SecretObject.

This method takes JSON-encoded strings or data structures and converts them into SecretObject instances, handling various data types.

Parameters

$jsonString

The JSON string to parse.

Return

SecretObject|null

The resulting SecretObject or null if the data is not valid.

MagicObject\Util\Database\DatabaseTypeConverter

Declaration

class DatabaseTypeConverter { }

Package

MagicObject\Util\Database

Description

Class DatabaseTypeConverter

Provides methods for converting database schema types between MySQL, PostgreSQL, and SQLite. It maps column data types from one database system to another to facilitate schema migration.

Conversion mappings are provided for:

  • MySQL to PostgreSQL and SQLite
  • PostgreSQL to MySQL and SQLite
  • SQLite to MySQL and PostgreSQL

    Use the conversion methods (mysqlToPostgresql, postgresqlToSQLite, etc.) to convert schema dumps from one format to another.

    Example:

    <?php
    $converter = new DatabaseTypeConverter();
    $postgresqlSchema = $converter->mysqlToPostgresql($mysqlSchema);

Constants

const TYPE_TINYINT_1 = "tinyint(1)";
const TYPE_DOUBLE_PRECISION = "double precision";
const TYPE_CHARACTER_VARYING = "character varying";

Properties

1. mysqlToPostgresql

Declaration

private array $mysqlToPostgresql = array ( 'tinyint(1)' => 'boolean', 'tinyint' => 'smallint', 'smallint' => 'smallint', 'int' => 'integer', 'bigint' => 'bigint', 'float' => 'real', 'double' => 'double precision', 'decimal' => 'numeric', 'varchar' => 'character varying', 'char' => 'character', 'text' => 'text', 'longtext' => 'text', 'tinytext' => 'text', 'datetime' => 'timestamp', 'timestamp' => 'timestamp with time zone', 'date' => 'date', 'time' => 'time', 'year' => 'smallint', 'json' => 'jsonb', 'uuid' => 'uuid', );

Description

Map of MySQL types to PostgreSQL types.

2. mysqlToSQLite

Declaration

private array $mysqlToSQLite = array ( 'tinyint(1)' => 'INTEGER', 'tinyint' => 'INTEGER', 'smallint' => 'INTEGER', 'int' => 'INTEGER', 'bigint' => 'INTEGER', 'float' => 'REAL', 'double' => 'REAL', 'decimal' => 'REAL', 'varchar' => 'NVARCHAR', 'char' => 'TEXT', 'longtext' => 'TEXT', 'text' => 'TEXT', 'tinytext' => 'TEXT', 'datetime' => 'DATETIME', 'timestamp' => 'TIMESTAMP', 'date' => 'DATE', 'time' => 'TIME', 'year' => 'INTEGER', 'json' => 'TEXT', 'uuid' => 'TEXT', );

Description

Map of MySQL types to SQLite types.

3. postgresqlToMySQL

Declaration

private array $postgresqlToMySQL = array ( 'boolean' => 'tinyint(1)', 'smallint' => 'smallint', 'integer' => 'int', 'bigint' => 'bigint', 'real' => 'float', 'double precision' => 'double', 'character varying' => 'varchar', 'character' => 'char', 'text' => 'text', 'timestamp' => 'datetime', 'timestamp with time zone' => 'timestamp', 'timestamptz' => 'timestamp', 'date' => 'date', 'time' => 'time', 'jsonb' => 'json', 'uuid' => 'uuid', );

Description

Map of PostgreSQL types to MySQL types.

4. postgresqlToSQLite

Declaration

private array $postgresqlToSQLite = array ( 'boolean' => 'INTEGER', 'smallint' => 'INTEGER', 'integer' => 'INTEGER', 'bigint' => 'INTEGER', 'real' => 'REAL', 'double precision' => 'REAL', 'character varying' => 'TEXT', 'character' => 'TEXT', 'text' => 'TEXT', 'timestamp' => 'TIMESTAMP', 'datetime' => 'DATETIME', 'date' => 'DATE', 'time' => 'TIME', 'jsonb' => 'TEXT', 'uuid' => 'TEXT', );

Description

Map of PostgreSQL types to SQLite types.

5. sqliteToMySQL

Declaration

private array $sqliteToMySQL = array ( 'NVARCHAR' => 'varchar', 'INTEGER' => 'int', 'REAL' => 'float', 'TEXT' => 'text', 'BLOB' => 'blob', );

Description

Map of SQLite types to MySQL types.

6. sqliteToPostgresql

Declaration

private array $sqliteToPostgresql = array ( 'NVARCHAR' => 'character varying', 'INTEGER' => 'integer', 'REAL' => 'real', 'TEXT' => 'text', 'BLOB' => 'bytea', );

Description

Map of SQLite types to PostgreSQL types.

Methods

1. mysqlToPostgresql

Declaration

public function mysqlToPostgresql(
    string $mysqlDump
) : string
{
}

Description

Convert MySQL schema to PostgreSQL schema.

Parameters

$mysqlDump

MySQL schema dump

Return

string

PostgreSQL schema

2. mysqlToSQLite

Declaration

public function mysqlToSQLite(
    string $mysqlDump
) : string
{
}

Description

Convert MySQL schema to SQLite schema.

Parameters

$mysqlDump

MySQL schema dump

Return

string

SQLite schema

3. postgresqlToMySQL

Declaration

public function postgresqlToMySQL(
    string $postgresqlDump
) : string
{
}

Description

Convert PostgreSQL schema to MySQL schema.

Parameters

$postgresqlDump

PostgreSQL schema dump

Return

string

MySQL schema

4. postgresqlToSQLite

Declaration

public function postgresqlToSQLite(
    string $postgresqlDump
) : string
{
}

Description

Convert PostgreSQL schema to SQLite schema.

Parameters

$postgresqlDump

PostgreSQL schema dump

Return

string

SQLite schema

5. sqliteToMySQL

Declaration

public function sqliteToMySQL(
    string $sqliteDump
) : string
{
}

Description

Convert SQLite schema to MySQL schema.

Parameters

$sqliteDump

SQLite schema dump

Return

string

MySQL schema

6. sqliteToPostgresql

Declaration

public function sqliteToPostgresql(
    string $sqliteDump
) : string
{
}

Description

Convert SQLite schema to PostgreSQL schema.

Parameters

$sqliteDump

SQLite schema dump

Return

string

PostgreSQL schema

7. convertSchema

Declaration

private function convertSchema(
    string $dump,
    array $typeMap
) : string
{
}

Description

Convert schema based on given type mapping.

Parameters

$dump

The schema dump

$typeMap

The type mapping to apply

Return

string

Converted schema

8. processCreateTable

Declaration

private function processCreateTable(
    string $createTableLine,
    array $lines,
    array $typeMap
) : string
{
}

Description

Process CREATE TABLE line and apply type conversions.

Parameters

$createTableLine

The CREATE TABLE statement

$lines

The schema lines

$typeMap

The type mapping to apply

Return

string

Converted CREATE TABLE statement

9. processColumn

Declaration

private function processColumn(
    string $columnDef,
    array $typeMap
) : string
{
}

Description

Process each column and apply type conversion.

Parameters

$columnDef

Column definition line

$typeMap

Type mapping to apply

Return

string

Converted column definition

10. convertType

Declaration

public function convertType(
    string $columnType,
    string $databaseType
) : string
{
}

Description

Converts a column type from MySQL to the target database type (PostgreSQL or SQLite).

This method takes a column type (e.g., "varchar", "int") and converts it to the appropriate data type for the specified target database (PostgreSQL or SQLite). It uses predefined mappings for MySQL to PostgreSQL and MySQL to SQLite conversions.

Parameters

$columnType

The column type to be converted (e.g., "varchar", "int").

$databaseType

The target database type. This can be one of the following:

Return

string

The corresponding column type for the target database, in uppercase.

MagicObject\Util\Database\EntityUtil

Declaration

class EntityUtil { }

Package

MagicObject\Util\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class EntityUtil

A utility class for managing database entities, providing methods to retrieve column names and map entity data to new keys. This class is designed to work with MagicObject instances and can handle various data formats, including arrays and stdClass objects.

Methods

1. getPropertyColumn

Declaration

public static function getPropertyColumn(
    MagicObject $entity
) : string[]
{
}

Description

Get the property column names from the entity.

Parameters

$entity

The input entity.

Return

string[]

An array of property column names.

2. getPropertyJoinColumn

Declaration

public static function getPropertyJoinColumn(
    MagicObject $entity
) : string[]
{
}

Description

Get the property join column names from the entity.

Parameters

$entity

The input entity.

Return

string[]

An array of property join column names.

3. getEntityData

Declaration

public static function getEntityData(
    array|stdClass|MagicObject $data,
    string[] $map
) : array
{
}

Description

Get entity data mapped to new keys.

Parameters

$data

Data to be mapped.

$map

An array mapping of keys.

Return

array

An array of mapped data.

4. fromArray

Declaration

private static function fromArray(
    array $data,
    string[] $map
) : array
{
}

Description

Map data from an array.

Parameters

$data

Data to map.

$map

An array mapping of keys.

Return

array

An array of mapped data.

5. fromStdClass

Declaration

private static function fromStdClass(
    stdClass $data,
    string[] $map
) : array
{
}

Description

Map data from a stdClass.

Parameters

$data

Data to map.

$map

An array mapping of keys.

Return

array

An array of mapped data.

6. fromMagicObject

Declaration

private static function fromMagicObject(
    MagicObject $data,
    string[] $map
) : array
{
}

Description

Map data from a MagicObject.

Parameters

$data

The input entity.

$map

An array mapping of keys.

Return

array

An array of mapped data.

MagicObject\Util\Database\NativeQueryUtil

Declaration

class NativeQueryUtil { }

Description

Utility class for working with SQL queries in the context of MagicObject's database operations.

The NativeQueryUtil class provides methods for handling SQL queries with dynamic parameters, pagination, and sorting. It includes functionality for generating modified query strings with array-type parameters, handling return types (e.g., PDOStatement, objects, arrays), extracting return types and queries from docblocks, and mapping PHP values to PDO parameter types. Additionally, it supports debugging by logging generated SQL queries.

Key responsibilities include:

  • Extracting SQL queries and return types from docblocks.
  • Converting PHP types into appropriate PDO parameter types.
  • Modifying query strings to handle array parameters and apply pagination/sorting.
  • Processing data returned from PDO statements and converting it to the expected return types.
  • Debugging SQL queries by sending them to a logger function.

Methods

1. applyQueryParameters

Declaration

public function applyQueryParameters(
    string $databaseType,
    string $queryString,
    ReflectionParameter[] $callerParams,
    array $callerParamValues
) : string
{
}

Description

Replaces array parameters and applies pagination and sorting to the query string.

This method processes the caller's parameters, replacing array-type parameters with string equivalents. It also adds pagination and sorting clauses if PicoPageable or PicoSortable objects are detected.

Parameters

$databaseType

The database type.

$queryString

The SQL query string with placeholders.

$callerParams

The parameters of the calling method (reflection objects).

$callerParamValues

The actual values of the parameters.

Return

string

The modified query string with array parameters replaced and pagination/sorting applied.

Throws

InvalidArgumentException

If parameters are in an unexpected format.

2. handleReturnObject

Declaration

public function handleReturnObject(
    PDOStatement $stmt,
    string $returnType
) : mixed
{
}

Description

Processes and returns data based on the specified return type.

This method handles various return types like void, PDOStatement, int, object, array, string, or any specific class name (including array-type hinting).

Parameters

$stmt

The executed PDO statement.

$returnType

The return type from the caller's docblock annotation.

Return

mixed

The processed return data (e.g., value, object, array, PDOStatement, or JSON string).

Throws

InvalidReturnTypeException

If the return type is invalid or unrecognized.

3. handleArrayReturnType

Declaration

private function handleArrayReturnType(
    PDOStatement $stmt,
    string $returnType
) : array
{
}

Description

Handles return types with array hinting (e.g., MagicObject[], MyClass[]).

Parameters

$stmt

The executed PDO statement.

$returnType

The array-type return type (e.g., MagicObject[]).

Return

array

The processed result as an array of objects.

Throws

InvalidReturnTypeException

If the return type is invalid or unrecognized.

4. handleSingleClassReturnType

Declaration

private function handleSingleClassReturnType(
    PDOStatement $stmt,
    string $returnType
) : mixed
{
}

Description

Handles return types that are a single object (e.g., MagicObject, MyClass).

Parameters

$stmt

The executed PDO statement.

$returnType

The single-class return type (e.g., MagicObject).

Return

mixed

The processed result as a single object.

Throws

InvalidReturnTypeException

If the return type is invalid or unrecognized.

5. mapRowsToMagicObject

Declaration

private function mapRowsToMagicObject(
    PDOStatement $stmt
) : MagicObject[]
{
}

Description

Maps rows from the PDO statement to an array of MagicObject instances.

Parameters

$stmt

The executed PDO statement.

Return

MagicObject[]

An array of MagicObject instances.

6. mapRowsToClass

Declaration

private function mapRowsToClass(
    PDOStatement $stmt,
    string $className
) : object[]
{
}

Description

Maps rows from the PDO statement to an array of instances of a specified class.

Parameters

$stmt

The executed PDO statement.

$className

The class name to map rows to.

Return

object[]

An array of instances of the specified class.

Throws

InvalidReturnTypeException

If the class does not exist.

7. extractReturnType

Declaration

public function extractReturnType(
    string $docComment,
    string $callerClassName
) : string
{
}

Description

Extracts the return type from the docblock of the caller function.

This method processes the @return annotation, handling self and array types, and returns the appropriate type, such as the caller class name or void.

Parameters

$docComment

The docblock of the caller function.

$callerClassName

The name of the class where the caller function is defined.

Return

string

The processed return type (class name, self, or void).

8. extractQueryString

Declaration

public function extractQueryString(
    string $docComment,
    array $callerParamValues
) : string
{
}

Description

Extracts the SQL query string from the docblock or caller's parameters.

This method checks the caller's parameters for a PicoDatabaseQueryTemplate object to extract the query string. If not found, it looks for the @query annotation in the docblock.

Parameters

$docComment

The docblock of the caller function.

$callerParamValues

The parameters passed to the caller.

Return

string

The extracted SQL query string.

Throws

InvalidQueryInputException

If no query string is found.

9. getQueryStringFromCallerParams

Declaration

private function getQueryStringFromCallerParams(
    array $callerParamValues
) : string
{
}

Description

Extracts the query string from the caller's parameters.

This method looks for a PicoDatabaseQueryTemplate object in the caller's parameters and returns the query string representation of that object.

Parameters

$callerParamValues

The parameters passed to the caller function.

Return

string

The SQL query string or an empty string if no valid object is found.

10. mapToPdoParamType

Declaration

public function mapToPdoParamType(
    mixed $value
) : stdClass
{
}

Description

Maps a value to the corresponding PDO parameter type.

This method determines the appropriate PDO parameter type based on the given value's type (e.g., null, boolean, integer, string, DateTime, or PicoSqlJson).

Parameters

$value

The value to determine the PDO parameter type for.

Return

stdClass

An object with:

11. debugQuery

Declaration

public function debugQuery(
    PicoDatabase $database,
    PDOStatement $stmt,
    array $params
) : void
{
}

Description

Sends an SQL query to a logger callback for debugging.

This method invokes the callback function defined in the database object, passing the final SQL query generated by combining the statement and parameters.

Parameters

$database

The database instance containing the callback.

$stmt

The prepared PDO statement.

$params

The parameters bound to the query.

Return

void

MagicObject\Util\Database\PicoDatabaseUtil

Declaration

class PicoDatabaseUtil { }

Package

MagicObject\Util\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseUtil

A utility class for handling database operations and specifications within the framework. This class provides methods to retrieve specifications, handle SQL query formatting, and manage data types, ensuring safe and efficient interactions with the database.

Constants

const INLINE_TRIM = " \r\n\t ";

Methods

2. specificationFromParams

Declaration

public static function specificationFromParams(
    array $params
) : PicoSpecification|null
{
}

Description

Retrieve a PicoSpecification instance from the given parameters.

This method iterates through the provided parameters to find and return the first instance of PicoSpecification. If none is found, null is returned.

Parameters

$params

An array of parameters to search.

Return

PicoSpecification|null

Returns the PicoSpecification instance or null if not found.

3. pageableFromParams

Declaration

public static function pageableFromParams(
    array $params
) : PicoPageable|null
{
}

Description

Retrieve a PicoPageable instance from the given parameters.

This method searches through the parameters for an instance of PicoPageable.

Parameters

$params

An array of parameters to search.

Return

PicoPageable|null

Returns the PicoPageable instance or null if not found.

4. sortableFromParams

Declaration

public static function sortableFromParams(
    array $params
) : PicoSortable|null
{
}

Description

Retrieve a PicoSortable instance from the given parameters.

This method looks for the first instance of PicoSortable in the parameters.

Parameters

$params

An array of parameters to search.

Return

PicoSortable|null

Returns the PicoSortable instance or null if not found.

5. valuesFromParams

Declaration

public static function valuesFromParams(
    array $params
) : array
{
}

Description

Retrieve values from the parameters until a PicoPageable instance is found.

This method collects and returns all parameters up to the first PicoPageable instance, effectively filtering the parameters.

Parameters

$params

An array of parameters to process.

Return

array

An array of values up to the first PicoPageable instance.

6. fixValue

Declaration

public static function fixValue(
    string $value,
    string $type
) : mixed
{
}

Description

Fix a value based on its expected type.

This method normalizes various representations of values (e.g., "true", "false", "null") into their appropriate PHP types based on the expected type.

Parameters

$value

The value to fix.

$type

The expected data type.

Return

mixed

The fixed value, converted to the appropriate type.

7. isNull

Declaration

public static function isNull(
    mixed $value,
    bool $importFromString
) : bool
{
}

Description

Check if a value is null.

This method checks if the provided value is null or represents "null" as a string.

Parameters

$value

The value to check.

$importFromString

Indicates if the input is from a string.

Return

bool

Returns true if the value is null or the string "null".

8. isNumeric

Declaration

public static function isNumeric(
    mixed $value,
    bool $importFromString
) : bool
{
}

Description

Check if a value is numeric.

This method checks if the value is a numeric string, specifically when the input is treated as a string.

Parameters

$value

The value to check.

$importFromString

Indicates if the input is from a string.

Return

bool

Returns true if the value is a numeric string and input is from a string.

9. escapeValue

Declaration

public static function escapeValue(
    mixed $value,
    bool $importFromString = false
) : string
{
}

Description

Escape a value for SQL.

This method prepares a value for safe SQL insertion by escaping it, handling various types including nulls, booleans, strings, and arrays.

Parameters

$value

The value to escape.

$importFromString

Indicates if the input is from a string.

Return

string

The escaped value suitable for SQL.

10. toList

Declaration

public static function toList(
    array $array,
    bool $bracket = false,
    bool $escape = false
) : string
{
}

Description

Convert an array to a list format for SQL queries.

This method converts an array into a comma-separated string representation, optionally enclosing the result in parentheses.

Parameters

$array

The array to convert.

$bracket

Indicates if the result should be enclosed in parentheses.

$escape

Indicates if the values should be escaped for SQL.

Return

string

The list representation of the array.

11. escapeSQL

Declaration

public static function escapeSQL(
    string $value
) : string
{
}

Description

Escape a SQL value to prevent SQL injection.

This method escapes special characters in a string to ensure safe SQL execution.

Parameters

$value

The value to escape.

Return

string

The escaped value.

12. trimWhere

Declaration

public static function trimWhere(
    string $where
) : string
{
}

Description

Trim a WHERE clause by removing unnecessary characters.

This method cleans up a raw WHERE clause by trimming whitespace and removing common redundant patterns.

Parameters

$where

The raw WHERE clause to be trimmed.

Return

string

The cleaned WHERE clause.

13. uuid

Declaration

public static function uuid() : string
{
}

Description

Generate a UUID.

Return

string

A generated UUID.

14. arrayFilterFunction

Declaration

private static function arrayFilterFunction(
    string $line
) : bool
{
}

Description

Filters out empty lines, comments (lines starting with "-- "), and lines that are exactly "--".

This function is commonly used in contexts where a list of lines or strings needs to be processed and filtered by excluding empty lines, comment lines (starting with "-- "), and lines with only the string "--".

Parameters

$line

The line to be checked.

Return

bool

Returns true if the line should be included, false otherwise.

15. getDelimiter

Declaration

private static function getDelimiter(
    string $line
) : string|null
{
}

Description

Determines the delimiter based on the second part of a trimmed line.

This function splits the given line by spaces and checks the second part. If the second part exists, it returns a semicolon (;) as the delimiter. Otherwise, it returns null.

Parameters

$line

The line to be analyzed, which is trimmed and split by spaces.

Return

string|null

Returns ';' if there is a second part after splitting the line, otherwise null.

16. splitSql

Declaration

public static function splitSql(
    string $sqlText
) : array
{
}

Description

Split a SQL string into separate queries.

This method takes a raw SQL string and splits it into individual queries based on delimiters, handling comments and whitespace.

Parameters

$sqlText

The raw SQL string containing one or more queries.

Return

array

An array of queries with their respective delimiters.

17. isArray

Declaration

public static function isArray(
    mixed $params
) : bool
{
}

Description

Check if a parameter is an array.

This method checks if the provided parameter is an array.

Parameters

$params

The parameter to check.

Return

bool

Returns true if the parameter is an array, false otherwise.

18. findInstanceInArray

Declaration

public static function findInstanceInArray(
    array $params,
    string $className
) : object|null
{
}

Description

Find an instance of a specified class in an array of parameters.

This method iterates through the parameters to find an instance of the specified class, returning it if found, or null otherwise.

Parameters

$params

An array of parameters to search.

$className

The name of the class to find.

Return

object|null

Returns the instance of the specified class or null if not found.

19. getFinalQuery

Declaration

public static function getFinalQuery(
    PDOStatement $stmt,
    array $params
) : string
{
}

Description

Retrieves the final query to be executed by the PDOStatement.

This function replaces the placeholders in the query with the bound parameter values.

Parameters

$stmt

The PDOStatement containing the original query.

$params

An array of parameter values to replace the placeholders.

Return

string

The final query with parameter values substituted.

MagicObject\Util\Database\PicoDatabaseUtilBase

Declaration

class PicoDatabaseUtilBase { }

Constants

const KEY_PRIMARY_KEY = "primary_key";
const KEY_NULLABLE = "nullable";
const KEY_AUTO_INCREMENT = "auto_increment";

Methods

1. getAutoIncrementKey

Declaration

public function getAutoIncrementKey(
    PicoTableInfo $tableInfo
) : array
{
}

Description

Gets the auto-increment keys from the provided table information.

Parameters

$tableInfo

Table information.

Return

array

An array of auto-increment key names.

2. isFetchingDataNotRequired

Declaration

private function isFetchingDataNotRequired(
    MagicObject $data,
    int $maxRecord,
    callable|null $callbackFunction
) : bool
{
}

Description

Determines whether fetching data is not required based on the provided parameters.

This method checks if fetching data is not necessary based on the specified conditions:

  • The getFindOption() of the $data object must have the FIND_OPTION_NO_FETCH_DATA flag set.
  • The $maxRecord must be greater than 0.
  • The $callbackFunction must be defined and callable.

Parameters

$data

The data object, typically an instance of MagicObject or similar.

$maxRecord

The maximum number of records to fetch.

$callbackFunction

Optional callback function that should be callable.

Return

bool

Returns true if fetching data is not required, otherwise false.

3. isArrayMagicObject

Declaration

private function isArrayMagicObject(
    mixed $data
) : bool
{
}

Description

Checks if the given data is an array of MagicObject instances.

This function checks whether the provided data is an array and whether the first element in the array is an instance of MagicObject. It is used to validate that the data structure is compatible with operations expecting an array of MagicObject instances.

Parameters

$data

The data to be checked.

Return

bool

Returns true if the data is an array and the first element is a MagicObject instance, otherwise false.

4. isCallbackFunction

Declaration

private function isCallbackFunction(
    mixed $callbackFunction
) : bool
{
}

Description

Checks if the provided callback function is callable.

This method checks whether the $callbackFunction is set and if it is a valid callable function. It ensures that the provided function can be invoked during the execution of the code.

Parameters

$callbackFunction

The callback function to be checked.

Return

bool

Returns true if the function is callable, otherwise false.

5. getRecords

Declaration

private function getRecords(
    string $picoTableName,
    array $columns,
    PicoPageData $data,
    int $maxRecord,
    callable|null $callbackFunction
) : array
{
}

Description

Fetches records from the provided data source and processes them in batches.

This method retrieves records from the specified data source (using a PDO statement) in batches, processes each record by mapping it to the required columns, and buffers the records until the specified maximum number is reached. When the batch size is met, the records are processed using an optional callback function, and the buffer is reset for the next batch.

Parameters

$picoTableName

The name of the target table where data will be inserted.

$columns

Array of columns to be used for processing each record.

$data

The data source containing records to be fetched, usually an instance of PicoPageData.

$maxRecord

The maximum number of records to fetch in a single query (default is 100).

$callbackFunction

Optional callback function to process the generated SQL

Return

array

An array of records that are fetched and processed. This will return the remaining

6. dumpData

Declaration

public function dumpData(
    array $columns,
    string $picoTableName,
    MagicObject|PicoPageData|array $data,
    int $maxRecord = 100,
    callable|null $callbackFunction = null
) : string|null
{
}

Description

Dumps data from various sources into SQL INSERT statements.

This method processes data from PicoPageData, MagicObject, or an array of MagicObject instances and generates SQL INSERT statements. It supports batching of records and allows for a callback function to handle the generated SQL statements.

Parameters

$columns

Array of columns for the target table.

$picoTableName

Name of the target table.

$data

Data to be dumped. Can be a PicoPageData instance,

$maxRecord

Maximum number of records to process in a single query (default is 100).

$callbackFunction

Optional callback function to process the generated SQL

Return

string|null

SQL INSERT statements or null if no data was processed.

7. dumpRecords

Declaration

public function dumpRecords(
    array $columns,
    string $picoTableName,
    MagicObject $record
) : string
{
}

Description

Constructs an SQL INSERT statement for a single record.

This method takes a data record and maps it to the corresponding columns of the target table, generating an SQL INSERT statement. It uses the PicoDatabaseQueryBuilder to build the query.

Parameters

$columns

Associative array mapping column names to their definitions in the target table.

$picoTableName

Name of the target table where the record will be inserted.

$record

The data record to be dumped into the SQL statement.

Return

string

The generated SQL INSERT statement.

8. getMaxRecord

Declaration

public function getMaxRecord(
    SecretObject $tableInfo,
    int $maxRecord
) : int
{
}

Description

Retrieves the maximum record limit for a query.

This method checks the specified table information for a maximum record value and ensures that the returned value is at least 1. If the table's maximum record limit is defined, it overrides the provided maximum record.

Parameters

$tableInfo

The table information containing maximum record settings.

$maxRecord

The maximum record limit per query specified by the user.

Return

int

The effective maximum record limit to be used in queries.

9. processDataMapping

Declaration

public function processDataMapping(
    mixed[] $data,
    string[] $columns,
    string[]|null $maps = null
) : mixed[]
{
}

Description

Processes data mapping according to specified column types and mappings.

This method updates the input data by mapping source fields to target fields based on the provided mappings, then filters and fixes the data types according to the column definitions.

Parameters

$data

The input data to be processed.

$columns

An associative array mapping column names to their types.

$maps

Optional array of mapping definitions in the format 'target:source'.

Return

mixed[]

The updated data array with fixed types and mappings applied.

10. createMapTemplate

Declaration

public function createMapTemplate(
    PicoDatabase $databaseSource,
    PicoDatabase $databaseTarget,
    string $target
) : string[]
{
}

Description

Creates a mapping template between source and target database tables.

This method generates a mapping array that indicates which columns in the target table do not exist in the source table, providing a template for further processing or data transformation.

Parameters

$databaseSource

The source database connection.

$databaseTarget

The target database connection.

$target

The name of the target table.

Return

string[]

An array of mapping strings indicating missing columns in the source.

11. updateConfigTable

Declaration

public function updateConfigTable(
    PicoDatabase $databaseSource,
    PicoDatabase $databaseTarget,
    array $tables,
    array $sourceTables,
    string $target,
    array $existingTables
) : array
{
}

Description

Automatically configures import data settings from one database to another.

This method checks if the target table exists in the existing tables. If it does not, it creates a new SecretObject for the table, determining whether the table is present in the source database and configuring the mapping accordingly.

Parameters

$databaseSource

The source database connection.

$databaseTarget

The target database connection.

$tables

The current array of table configurations.

$sourceTables

List of source table names.

$target

The name of the target table to be configured.

$existingTables

List of existing tables in the target database.

Return

array

Updated array of table configurations with the new table info added if applicable.

12. importDataTable

Declaration

public function importDataTable(
    PicoDatabase $databaseSource,
    PicoDatabase $databaseTarget,
    string $tableNameSource,
    string $tableNameTarget,
    SecretObject $tableInfo,
    int $maxRecord,
    callable $callbackFunction
) : bool
{
}

Description

Imports data from a source database table to a target database table.

This method fetches records from the specified source table and processes them according to the provided mapping and column information. It uses a callback function to handle the generated SQL insert statements in batches, up to a specified maximum record count.

Parameters

$databaseSource

The source database from which to import data.

$databaseTarget

The target database where data will be inserted.

$tableNameSource

The name of the source table.

$tableNameTarget

The name of the target table.

$tableInfo

Information about the table, including mapping and constraints.

$maxRecord

The maximum number of records to process in a single batch.

$callbackFunction

A callback function to handle the generated SQL statements.

Return

bool

True on success, false on failure.

13. importData

Declaration

public function importData(
    SecretObject $config,
    callable $callbackFunction
) : bool
{
}

Description

Imports data from the source database to the target database.

This method connects to the source and target databases, executes any pre-import scripts, transfers data from the source tables to the target tables, and executes any post-import scripts.

Parameters

$config

Configuration object containing database and table details.

$callbackFunction

Callback function to execute SQL scripts.

Return

bool

Returns true on successful import, false on failure.

14. fixData

Declaration

public function fixData(
    mixed $value
) : string
{
}

Description

Fixes data for safe use in SQL queries.

This method processes a given value and formats it as a string suitable for SQL. It handles strings, booleans, nulls, and other data types appropriately.

Parameters

$value

The value to be processed.

Return

string

The formatted string representation of the value.

15. fixBooleanData

Declaration

public function fixBooleanData(
    mixed[] $data,
    string $name,
    mixed $value
) : mixed[]
{
}

Description

Fixes boolean data in the provided array.

This method updates the specified key in the input array to ensure that its value is a boolean. If the value is null or an empty string, it sets the key to null. Otherwise, it converts the value to a boolean based on the condition that if it equals 1, it is set to true; otherwise, false.

Parameters

$data

The input array containing data.

$name

The key in the array to update.

$value

The value to be processed.

Return

mixed[]

The updated array with the fixed boolean data.

16. fixIntegerData

Declaration

public function fixIntegerData(
    mixed[] $data,
    string $name,
    mixed $value
) : mixed[]
{
}

Description

Fixes integer data in the provided array.

This method updates the specified key in the input array to ensure that its value is an integer. If the value is null or an empty string, it sets the key to null. Otherwise, it converts the value to an integer.

Parameters

$data

The input array containing data.

$name

The key in the array to update.

$value

The value to be processed.

Return

mixed[]

The updated array with the fixed integer data.

17. fixFloatData

Declaration

public function fixFloatData(
    mixed[] $data,
    string $name,
    mixed $value
) : mixed[]
{
}

Description

Fixes float data in the provided array.

This method updates the specified key in the input array to ensure that its value is a float. If the value is null or an empty string, it sets the key to null. Otherwise, it converts the value to a float.

Parameters

$data

The input array containing data.

$name

The key in the array to update.

$value

The value to be processed.

Return

mixed[]

The updated array with the fixed float data.

18. insert

Declaration

public function insert(
    string $tableName,
    array $data
) : string
{
}

Description

Creates an SQL INSERT query for multiple records.

This method generates an INSERT statement for a specified table and prepares the values for binding in a batch operation. It supports multiple records and ensures proper formatting of values.

Parameters

$tableName

Name of the table where data will be inserted.

$data

An array of associative arrays, where each associative array

Return

string

The generated SQL INSERT statement with placeholders for values.

19. dumpRecord

Declaration

public function dumpRecord(
    array $columns,
    string $picoTableName,
    MagicObject $record
) : string
{
}

Description

Dumps a single record into an SQL insert statement.

Parameters

$columns

Columns of the target table.

$picoTableName

Table name.

$record

Data record.

Return

string

SQL insert statement.

20. fixImportData

Declaration

public function fixImportData(
    mixed[] $data,
    string[] $columns
) : mixed[]
{
}

Description

Fixes imported data based on specified column types.

This method processes the input data array and adjusts the values according to the expected types defined in the columns array. It supports boolean, integer, and float types.

Parameters

$data

The input data to be processed.

$columns

An associative array mapping column names to their types.

Return

mixed[]

The updated data array with fixed types.

21. showColumns

Declaration

public function showColumns(
    PicoDatabase $database,
    string $tableName
) : array
{
}

Description

Retrieves the columns of a specified table from the database.

This method executes a SQL query to show the columns of the given table and returns an associative array where the keys are column names and the values are their respective types.

Parameters

$database

Database connection object.

$tableName

Name of the table whose columns are to be retrieved.

Return

array

An associative array mapping column names to their types.

Throws

Exception

If the query fails or the table does not exist.

22. convertMySqlToPostgreSql

Declaration

public function convertMySqlToPostgreSql(
    string $mysqlQuery
) : string
{
}

Description

Converts a MySQL CREATE TABLE query to a PostgreSQL compatible query.

This function takes a SQL CREATE TABLE statement written for MySQL and transforms it into a format compatible with PostgreSQL. It handles common data types, constraints, and syntax differences between the two databases, such as converting data types, removing unsupported clauses (e.g., AUTO_INCREMENT, ENGINE), and adjusting default values and column types.

Parameters

$mysqlQuery

The MySQL CREATE TABLE query to be converted.

Return

string

The converted PostgreSQL CREATE TABLE query, with MySQL-specific syntax

Throws

InvalidArgumentException

If the input query is not a valid MySQL CREATE TABLE query.

23. convertPostgreSqlToMySql

Declaration

public function convertPostgreSqlToMySql(
    string $postgresqlQuery
) : string
{
}

Description

Converts a PostgreSQL CREATE TABLE query to a MySQL compatible query.

This function takes a SQL CREATE TABLE statement written for PostgreSQL and transforms it into a format compatible with MySQL. It handles common data types, constraints, and syntax differences between the two databases. The function adjusts data types, removes PostgreSQL-specific clauses, and makes necessary adjustments for MySQL compatibility.

Parameters

$postgresqlQuery

The PostgreSQL CREATE TABLE query to be converted.

Return

string

The converted MySQL CREATE TABLE query, with PostgreSQL-specific syntax

Throws

InvalidArgumentException

If the input query is not a valid PostgreSQL CREATE TABLE query.

24. isNativeValue

Declaration

public static function isNativeValue(
    string $defaultValue
) : bool
{
}

Description

Checks if the given value is a native value (true, false, or null).

This function checks if the provided $defaultValue is a string representing one of the native values: "true", "false", or "null".

Parameters

$defaultValue

The value to check.

Return

bool

True if the value is "true", "false", or "null", false otherwise.

25. isTypeBoolean

Declaration

public static function isTypeBoolean(
    string $type
) : bool
{
}

Description

Checks if the given type is a boolean type.

This function checks if the provided $type contains the word "bool", indicating it is a boolean type (e.g., bool, boolean).

Parameters

$type

The type to check.

Return

bool

True if the type contains "bool", false otherwise.

26. isTypeText

Declaration

public static function isTypeText(
    string $type
) : bool
{
}

Description

Checks if the given type is a text-based type.

This function checks if the provided $type contains the word "enum", "varchar", "char", or "text", indicating it is a text-based type (e.g., enum, varchar, char, text).

Parameters

$type

The type to check.

Return

bool

True if the type contains "enum", "varchar", "char", or "text", false otherwise.

27. isTypeInteger

Declaration

public static function isTypeInteger(
    string $type
) : bool
{
}

Description

Checks if the given type is an integer type.

This function checks if the provided $type contains the word "int", indicating it is an integer type (e.g., int, integer).

Parameters

$type

The type to check.

Return

bool

True if the type contains "int", false otherwise.

28. isTypeFloat

Declaration

public static function isTypeFloat(
    string $type
) : bool
{
}

Description

Checks if the given type is a float type.

This function checks if the provided $type contains any of the words "decimal", "float", "double", or "real", indicating it is a floating-point type.

Parameters

$type

The type to check.

Return

bool

True if the type contains "decimal", "float", "double", or "real", false otherwise.

29. isArray

Declaration

public static function isArray(
    mixed $value
) : bool
{
}

Description

Checks if the given value is an array.

This function checks if the provided $value is set and is an array.

Parameters

$value

The value to check.

Return

bool

True if the value is an array, false otherwise.

30. isNotEmpty

Declaration

public function isNotEmpty(
    array $array
) : bool
{
}

Description

Checks if the provided array is not empty.

This method verifies that the input is an array and contains at least one element.

Parameters

$array

The array to be checked.

Return

bool

True if the array is not empty; otherwise, false.

MagicObject\Util\Database\PicoDatabaseUtilInterface

Declaration

class PicoDatabaseUtilInterface { }

Description

Interface PicoDatabaseUtilInterface

Defines methods for managing database structures and data, including table and column management, data import/export, and database configuration.

Key methods include:

  • Retrieving column lists from tables.
  • Handling auto-increment keys.
  • Generating SQL for creating/dropping tables.
  • Configuring columns, fixing defaults, and importing data.
  • Mapping and correcting data types during import.

    Implementations must ensure data integrity, validation, and error handling during operations.

Methods

MagicObject\Util\Database\PicoDatabaseUtilMySql

Declaration

class PicoDatabaseUtilMySql extends MagicObject\Util\Database\PicoDatabaseUtilBase implements MagicObject\Util\Database\PicoDatabaseUtilInterface { }

Package

MagicObject\Util\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseUtilMySql

Provides utility methods for MySQL database operations, extending PicoDatabaseUtilBase and implementing PicoDatabaseUtilInterface. This class includes functions for retrieving column information, generating CREATE TABLE statements, dumping data to SQL insert statements, facilitating data imports, and ensuring data integrity during the import process.

Key features:

  • Retrieve column info from MySQL tables.
  • Generate CREATE TABLE statements.
  • Convert data to SQL INSERT statements.
  • Facilitate data import between databases.
  • Ensure data integrity during imports.

    Designed for developers working with MySQL to streamline database management tasks.

Methods

1. getColumnList

Declaration

public function getColumnList(
    PicoDatabase $database,
    string $tableName
) : array
{
}

Description

Retrieves a list of columns for a specified table.

Parameters

$database

Database connection.

$tableName

Table name.

Return

array

An array of column details.

2. dumpStructure

Declaration

public function dumpStructure(
    PicoTableInfoExtended $tableInfo,
    string $tableName,
    bool $createIfNotExists = false,
    bool $dropIfExists = false,
    string|null $engine = 'InnoDB',
    string|null $charset = 'utf8mb4'
) : string
{
}

Description

Dumps the structure of a table as a SQL statement.

This method generates a SQL CREATE TABLE statement based on the provided table information, including the option to include or exclude specific clauses such as "IF NOT EXISTS" and "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.

Parameters

$tableInfo

The information about the table, including column details and primary keys.

$tableName

The name of the table for which the structure is being generated.

$createIfNotExists

Whether to add "IF NOT EXISTS" in the CREATE statement (default is false).

$dropIfExists

Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).

$engine

The storage engine to use for the table (optional, default is null).

$charset

The character set to use for the table (optional, default is null).

Return

string

The SQL statement to create the table, including column definitions and primary keys.

3. createColumn

Declaration

public function createColumn(
    array $column,
    array $autoIncrementKeys,
    array $primaryKeys
) : string
{
}

Description

Creates a column definition for a SQL statement.

This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, default value, primary key status, and auto-increment settings. The resulting definition is formatted for use in a CREATE TABLE statement.

Parameters

$column

An associative array containing details about the column:

$autoIncrementKeys

An array of column names that should have AUTO_INCREMENT property.

$primaryKeys

An array of primary key columns, each being an associative array

Return

string

The SQL column definition formatted as a string, suitable for inclusion in a CREATE TABLE statement.

4. fixDefaultValue

Declaration

public function fixDefaultValue(
    mixed $defaultValue,
    string $type
) : mixed
{
}

Description

Fixes the default value for SQL insertion based on its type.

This method processes the given default value according to the specified data type, ensuring that it is correctly formatted for SQL insertion. For string-like types, the value is enclosed in single quotes, while boolean and null values are returned as is.

Parameters

$defaultValue

The default value to fix, which can be a string, boolean, or null.

$type

The data type of the column (e.g., ENUM, CHAR, TEXT, INT, FLOAT, DOUBLE).

Return

mixed

The fixed default value formatted appropriately for SQL insertion.

7. autoConfigureImportData

Declaration

public function autoConfigureImportData(
    SecretObject $config
) : SecretObject
{
}

Description

Automatically configures the import data settings based on the source and target databases.

This method connects to the source and target databases, retrieves the list of existing tables, and updates the configuration for each target table by checking its presence in the source database. It handles exceptions and logs any errors encountered during the process.

Parameters

$config

The configuration object containing database and table information.

Return

SecretObject

The updated configuration object with modified table settings.

9. getColumnType

Declaration

public function getColumnType(
    string $columnType
) : string
{
}

Description

Returns the given column type without modification.

This method simply returns the column type passed as an argument. It is useful when no conversion is needed, and you want to retrieve the column type as-is.

Parameters

$columnType

The column type to be returned.

Return

string

The same column type passed as input.

MagicObject\Util\Database\PicoDatabaseUtilPostgreSql

Declaration

class PicoDatabaseUtilPostgreSql extends MagicObject\Util\Database\PicoDatabaseUtilBase implements MagicObject\Util\Database\PicoDatabaseUtilInterface { }

Package

MagicObject\Util\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseUtilPostgreSql

Provides utility methods for PostgreSQL database operations, extending PicoDatabaseUtilBase and implementing PicoDatabaseUtilInterface. It includes functions for retrieving column information, generating CREATE TABLE statements, dumping data to SQL insert statements, importing data, and ensuring data integrity during imports.

Key features:

  • Retrieve column info from PostgreSQL tables.
  • Generate CREATE TABLE statements.
  • Convert data to SQL INSERT statements.
  • Facilitate data import between databases.
  • Fix data types for integrity during imports.

    Designed for developers working with PostgreSQL to manage database tasks efficiently.

Methods

1. getColumnList

Declaration

public function getColumnList(
    PicoDatabase $database,
    string $tableName
) : array
{
}

Description

Retrieves a list of columns for a specified table in the database.

This method queries the information schema to obtain details about the columns of the specified table, including their names, data types, nullability, and default values.

Parameters

$database

The database connection instance.

$tableName

The name of the table to retrieve column information from.

Return

array

An array of associative arrays containing details about each column,

Throws

Exception

If the database connection fails or the query cannot be executed.

2. dumpStructure

Declaration

public function dumpStructure(
    PicoTableInfoExtended $tableInfo,
    string $tableName,
    bool $createIfNotExists = false,
    bool $dropIfExists = false,
    string|null $engine = null,
    string|null $charset = null
) : string
{
}

Description

Dumps the structure of a table as a SQL statement.

This method generates a SQL CREATE TABLE statement based on the provided table information, including options to add or omit specific clauses such as "IF NOT EXISTS" and "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.

Parameters

$tableInfo

The information about the table, including column details and primary keys.

$tableName

The name of the table for which the structure is being generated.

$createIfNotExists

Whether to include "IF NOT EXISTS" in the CREATE statement (default is false).

$dropIfExists

Whether to include "DROP TABLE IF EXISTS" before the CREATE statement (default is false).

$engine

The storage engine to use for the table (optional, default is null).

$charset

The character set to use for the table (optional, default is null).

Return

string

The SQL statement to create the table, including column definitions and primary keys.

3. createColumn

Declaration

public function createColumn(
    array $column
) : string
{
}

Description

Creates a column definition for a SQL statement.

This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, and default value. The resulting definition is formatted for use in a CREATE TABLE statement.

Parameters

$column

An associative array containing details about the column:

Return

string

The SQL column definition formatted as a string, suitable for inclusion in a CREATE TABLE statement.

4. fixAutoIncrementType

Declaration

private function fixAutoIncrementType(
    array $column,
    string $type,
    array $autoIncrementKeys
) : string
{
}

Description

Adjusts the SQL data type for auto-increment columns.

This method checks if the given column is designated as an auto-increment key and modifies its SQL type accordingly. If the column is a big integer, it will return "BIGSERIAL"; otherwise, it will return "SERIAL" for standard integer types. If the column is not an auto-increment key, it returns the original type.

Parameters

$column

An associative array containing details about the column,

$type

The original data type of the column.

$autoIncrementKeys

An array of column names that are designated as

Return

string

The adjusted SQL data type for the column, suitable for use

5. createColumnPostgre

Declaration

public function createColumnPostgre(
    array $column,
    array|null $autoIncrementKeys,
    array $primaryKeys
) : string
{
}

Description

Creates a column definition for a PostgreSQL SQL statement.

This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, default value, and whether the column should be auto-incrementing. If the column is specified as auto-increment, it will use PostgreSQL's SERIAL or BIGSERIAL data types, depending on the column type.

Parameters

$column

An associative array containing details about the column:

$autoIncrementKeys

An optional array of column names that should

$primaryKeys

An array of primary key columns, each being an associative

Return

string

The SQL column definition formatted as a string, suitable for inclusion

6. fixDefaultValue

Declaration

public function fixDefaultValue(
    mixed $defaultValue,
    string $type
) : mixed
{
}

Description

Fixes the default value for SQL insertion based on its type.

This method processes the given default value according to the specified data type, ensuring that it is correctly formatted for SQL insertion. For string-like types, the value is enclosed in single quotes, while boolean and null values are returned as is.

Parameters

$defaultValue

The default value to fix, which can be a string, boolean, or null.

$type

The data type of the column (e.g., ENUM, CHAR, TEXT, INT, FLOAT, DOUBLE).

Return

mixed

The fixed default value formatted appropriately for SQL insertion.

9. autoConfigureImportData

Declaration

public function autoConfigureImportData(
    SecretObject $config
) : SecretObject
{
}

Description

Automatically configures the import data settings based on the source and target databases.

This method connects to the source and target databases, retrieves the list of existing tables, and updates the configuration for each target table by checking its presence in the source database. It handles exceptions and logs any errors encountered during the process.

Parameters

$config

The configuration object containing database and table information.

Return

SecretObject

The updated configuration object with modified table settings.

11. getColumnType

Declaration

public function getColumnType(
    string $columnType
) : string
{
}

Description

Converts the given column type from MySQL format to PostgreSQL format.

This method calls the convertMySqlToPostgreSql function to perform the conversion of the column type from MySQL to PostgreSQL syntax. The method provides an abstraction layer for converting column types, ensuring compatibility when migrating between MySQL and PostgreSQL.

Parameters

$columnType

The MySQL column type to be converted.

Return

string

The equivalent PostgreSQL column type.

Throws

InvalidArgumentException

If the column type is not recognized or unsupported.

MagicObject\Util\Database\PicoDatabaseUtilSqlite

Declaration

class PicoDatabaseUtilSqlite extends MagicObject\Util\Database\PicoDatabaseUtilBase implements MagicObject\Util\Database\PicoDatabaseUtilInterface { }

Package

MagicObject\Util\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseUtilSqlite

Provides utility methods for SQLite database operations, extending PicoDatabaseUtilBase and implementing PicoDatabaseUtilInterface. This class includes functions for retrieving column information, generating CREATE TABLE statements, dumping data to SQL insert statements, facilitating data imports, and ensuring data integrity during the import process.

Key features:

  • Retrieve column info from SQLite tables.
  • Generate CREATE TABLE statements.
  • Convert data to SQL INSERT statements.
  • Facilitate data import between databases.
  • Ensure data integrity during imports.

    Designed for developers working with SQLite to streamline database management tasks.

Methods

1. showCreateTable

Declaration

public function showCreateTable(
    MagicObject $entity,
    bool $createIfNotExists = false,
    bool $dropIfExists = false
) : string
{
}

Description

Generates a SQL CREATE TABLE query based on the provided class annotations.

This function inspects the given class for its properties and their annotations to construct a SQL statement that can be used to create a corresponding table in a database. It extracts the table name from the @Table annotation and processes each property to determine the column definitions from the @Column annotations.

Parameters

$entity

The instance of the class whose properties will be used

$createIfNotExists

If true, the query will include an "IF NOT EXISTS" clause.

$dropIfExists

Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).

Return

string

The generated SQL CREATE TABLE query.

Throws

ReflectionException

If the class does not exist or is not accessible.

2. createIfNotExists

Declaration

private function createIfNotExists(
    bool $createIfNotExists
) : string
{
}

Description

Returns "IF NOT EXISTS" if specified, otherwise an empty string.

Parameters

$createIfNotExists

Flag indicating whether to include "IF NOT EXISTS".

Return

string

The "IF NOT EXISTS" clause if applicable.

3. getPkeyArrayFinal

Declaration

private function getPkeyArrayFinal(
    array $pKeyArr,
    array $pKeyArrUsed
) : array
{
}

Description

Filter the primary key array to exclude used primary keys.

Parameters

$pKeyArr

Array of primary key names.

$pKeyArrUsed

Array of used primary key names.

Return

array

Filtered array of primary key names.

4. determineSqlType

Declaration

private function determineSqlType(
    array $column,
    array|null $autoIncrementKeys = null,
    int $length = 255,
    array $pKeyArrUsed = array ( )
) : array
{
}

Description

Determine the SQL data type based on the given column information and auto-increment keys.

Parameters

$column

The column information, expected to include the column name and type.

$autoIncrementKeys

The array of auto-increment keys, if any.

$length

The length for VARCHAR types.

$pKeyArrUsed

The array to store used primary key names.

Return

array

An array containing the determined SQL data type and the updated primary key array.

5. getColumnList

Declaration

public function getColumnList(
    PicoDatabase $database,
    string $tableName
) : array
{
}

Description

Retrieves a list of columns for a specified table in the database.

This method queries the information schema to obtain details about the columns of the specified table, including their names, data types, nullability, default values, and any additional attributes such as primary keys and auto-increment.

Parameters

$database

The database connection instance.

$tableName

The name of the table to retrieve column information from.

Return

array

An array of associative arrays containing details about each column,

Throws

Exception

If the database connection fails or the query cannot be executed.

6. dumpStructure

Declaration

public function dumpStructure(
    PicoTableInfoExtended $tableInfo,
    string $tableName,
    bool $createIfNotExists = false,
    bool $dropIfExists = false,
    string|null $engine = 'InnoDB',
    string|null $charset = 'utf8mb4'
) : string
{
}

Description

Dumps the structure of a table as a SQL statement.

This method generates a SQL CREATE TABLE statement based on the provided table information, including the option to include or exclude specific clauses such as "IF NOT EXISTS" and "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.

Parameters

$tableInfo

The information about the table, including column details and primary keys.

$tableName

The name of the table for which the structure is being generated.

$createIfNotExists

Whether to add "IF NOT EXISTS" in the CREATE statement (default is false).

$dropIfExists

Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).

$engine

The storage engine to use for the table (optional, default is null).

$charset

The character set to use for the table (optional, default is null).

Return

string

The SQL statement to create the table, including column definitions and primary keys.

7. mysqlToSqliteType

Declaration

private function mysqlToSqliteType(
    string $type
) : string
{
}

Description

Converts MySQL data types to SQLite-compatible types.

This function maps MySQL data types to their equivalent SQLite types. It supports:

  • tinyint(1) to BOOLEAN,
  • integer to INTEGER,
  • enum() to NVARCHAR(N) with a length based on the maximum length of the enum values plus 2,
  • varchar(N) to NVARCHAR(N) (or varchar to NVARCHAR without a length),
  • float, double to REAL,
  • decimal to NUMERIC,
  • text and longtext to TEXT,
  • date, datetime, timestamp to TEXT (as SQLite does not have dedicated date/time types).

Parameters

$type

The MySQL data type to convert (e.g., 'tinyint(1)', 'varchar(255)', 'enum(', 'decimal(10,2)').

Return

string

The corresponding SQLite data type (e.g., 'BOOLEAN', 'NVARCHAR(255)', 'REAL', 'NUMERIC', 'TEXT').

8. createColumn

Declaration

public function createColumn(
    array $column
) : string
{
}

Description

Creates a column definition for a SQL statement (SQLite).

This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, default value, and primary key constraints. The resulting definition is formatted for use in a CREATE TABLE statement, suitable for SQLite.

If the column is specified as a primary key with auto-increment, the column type is set to INTEGER, and the PRIMARY KEY constraint is added with auto-increment behavior (SQLite uses INTEGER PRIMARY KEY AUTOINCREMENT).

Parameters

$column

An associative array containing details about the column:

Return

string

The SQL column definition formatted as a string, suitable for inclusion

9. fixDefaultValue

Declaration

public function fixDefaultValue(
    mixed $defaultValue,
    string $type
) : mixed
{
}

Description

Fixes the default value for SQL insertion based on its type.

This method processes the given default value according to the specified data type, ensuring that it is correctly formatted for SQL insertion. For string-like types, the value is enclosed in single quotes, while boolean and null values are returned as is.

Parameters

$defaultValue

The default value to fix, which can be a string, boolean, or null.

$type

The data type of the column (e.g., ENUM, CHAR, TEXT, INT, FLOAT, DOUBLE).

Return

mixed

The fixed default value formatted appropriately for SQL insertion.

11. autoConfigureImportData

Declaration

public function autoConfigureImportData(
    SecretObject $config
) : SecretObject
{
}

Description

Automatically configures the import data settings based on the source and target databases.

This method connects to the source and target databases, retrieves the list of existing tables, and updates the configuration for each target table by checking its presence in the source database. It handles exceptions and logs any errors encountered during the process.

Parameters

$config

The configuration object containing database and table information.

Return

SecretObject

The updated configuration object with modified table settings.

12. tableExists

Declaration

public function tableExists(
    PicoDatabase $database,
    string $tableName
) : bool
{
}

Description

Check if a table exists in the database.

This method queries the database to determine if a specified table exists by checking the SQLite master table. It throws an exception if the table name is null or empty.

Parameters

$database

The database instance to check.

$tableName

The name of the table to check.

Return

bool

True if the table exists, false otherwise.

Throws

InvalidParameterException

If the table name is null or empty.

13. getColumnType

Declaration

public function getColumnType(
    string $columnType
) : string
{
}

Description

Converts a MySQL column type to its equivalent SQLite column type.

This method uses the mysqlToSqliteType function to convert a MySQL column type to the appropriate SQLite column type. It helps facilitate database migration or compatibility between MySQL and SQLite.

Parameters

$columnType

The MySQL column type to be converted.

Return

string

The equivalent SQLite column type.

Throws

InvalidArgumentException

If the column type is not recognized or unsupported.

MagicObject\Util\Database\PicoDatabaseUtilSqlServer

Declaration

class PicoDatabaseUtilSqlServer extends MagicObject\Util\Database\PicoDatabaseUtilBase implements MagicObject\Util\Database\PicoDatabaseUtilInterface { }

Package

MagicObject\Util\Database

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDatabaseUtilSqlServer

Provides utility methods for SQL Server database operations, extending PicoDatabaseUtilBase and implementing PicoDatabaseUtilInterface. This class includes functions for retrieving column information, generating CREATE TABLE statements, dumping data to SQL insert statements, facilitating data imports, and ensuring data integrity during the import process.

Key features:

  • Retrieve column info from SQL Server tables.
  • Generate CREATE TABLE statements.
  • Convert data to SQL INSERT statements.
  • Facilitate data import between databases.
  • Ensure data integrity during imports.

    Designed for developers working with SQL Server to streamline database management tasks.

Constants

const TINYINT_1 = "tinyint(1)";

Methods

1. getColumnList

Declaration

public function getColumnList(
    PicoDatabase $database,
    string $tableName
) : array
{
}

Description

Retrieves a list of columns for a specified table in SQL Server.

This method queries the system views to obtain details about the columns of the specified table, including their names, data types, nullability, default values, and whether they are part of the primary key.

Parameters

$database

The database connection instance.

$tableName

The name of the table to retrieve column information from.

Return

array

An array of associative arrays containing details about each column,

Throws

Exception

If the database connection fails or the query cannot be executed.

2. dumpStructure

Declaration

public function dumpStructure(
    PicoTableInfoExtended $tableInfo,
    string $tableName,
    bool $createIfNotExists = false,
    bool $dropIfExists = false,
    string|null $engine = 'InnoDB',
    string|null $charset = 'utf8mb4'
) : string
{
}

Description

Dumps the structure of a table as a SQL statement for SQL Server.

This method generates a SQL CREATE TABLE statement based on the provided table information, including the option to include or exclude specific clauses such as "IF NOT EXISTS" and "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.

Parameters

$tableInfo

The information about the table, including column details and primary keys.

$tableName

The name of the table for which the structure is being generated.

$createIfNotExists

Whether to add "IF NOT EXISTS" in the CREATE statement (default is false).

$dropIfExists

Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).

$engine

The storage engine to use for the table (optional, default is null).

$charset

The character set to use for the table (optional, default is null).

Return

string

The SQL statement to create the table, including column definitions and primary keys.

3. createColumn

Declaration

public function createColumn(
    array $column,
    array $autoIncrementKeys,
    array $primaryKeys
) : string
{
}

Description

Creates a column definition for a SQL statement for SQL Server.

This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, default value, primary key status, and auto-increment settings. The resulting definition is formatted for use in a CREATE TABLE statement.

Parameters

$column

An associative array containing details about the column:

$autoIncrementKeys

An array of column names that should have IDENTITY(1,1) property.

$primaryKeys

An array of primary key columns, each being an associative array

Return

string

The SQL column definition formatted as a string, suitable for inclusion in a CREATE TABLE statement.

4. fixDefaultValue

Declaration

public function fixDefaultValue(
    mixed $defaultValue,
    string $type
) : mixed
{
}

Description

Fixes the default value for SQL insertion based on its type.

This method processes the given default value according to the specified data type, ensuring that it is correctly formatted for SQL insertion. For string-like types, the value is enclosed in single quotes, while boolean and null values are returned as is.

Parameters

$defaultValue

The default value to fix, which can be a string, boolean, or null.

$type

The data type of the column (e.g., ENUM, CHAR, TEXT, INT, FLOAT, DOUBLE).

Return

mixed

The fixed default value formatted appropriately for SQL insertion.

7. autoConfigureImportData

Declaration

public function autoConfigureImportData(
    SecretObject $config
) : SecretObject
{
}

Description

Automatically configures the import data settings based on the source and target databases.

This method connects to the source and target databases, retrieves the list of existing tables, and updates the configuration for each target table by checking its presence in the source database. It handles exceptions and logs any errors encountered during the process.

Parameters

$config

The configuration object containing database and table information.

Return

SecretObject

The updated configuration object with modified table settings.

9. getColumnType

Declaration

public function getColumnType(
    string $columnType
) : string
{
}

Description

Converts the given column type from MySQL format to SQL Server format.

This method performs the conversion of the column type from MySQL to SQL Server syntax. It ensures compatibility when migrating column types from MySQL to SQL Server.

Parameters

$columnType

The MySQL column type to be converted.

Return

string

The equivalent SQL Server column type.

Throws

InvalidArgumentException

If the column type is not recognized or unsupported.

10. convertMySqlToSqlServer

Declaration

public function convertMySqlToSqlServer(
    string $mysqlQuery
) : string
{
}

Description

Converts a MySQL CREATE TABLE query to a SQL Server compatible query.

This function takes a SQL CREATE TABLE statement written for MySQL and transforms it into a format compatible with SQL Server. It handles common data types, constraints, and syntax differences between the two databases, such as converting data types, removing unsupported clauses (e.g., AUTO_INCREMENT), and adjusting default values and column types.

Parameters

$mysqlQuery

The MySQL CREATE TABLE query to be converted.

Return

string

The converted SQL Server CREATE TABLE query, with MySQL-specific syntax

Throws

InvalidArgumentException

If the input query is not a valid MySQL CREATE TABLE query.

MagicObject\Util\Database\PicoQueryTranslator

Declaration

class PicoQueryTranslator { }

Package

MagicObject\Util\Database

Description

Class PicoQueryTranslator

This class is responsible for translating database query structures between different SQL dialects. It takes SQL queries written in one dialect (e.g., MySQL) and converts them into another dialect (e.g., PostgreSQL, SQLite). The class handles differences in syntax, keywords, functions, and other database-specific features.

Key functionalities of this class include:

  • Translating data types between different SQL flavors.
  • Adjusting query syntax to match the conventions of different database systems.
  • Converting SQL-specific expressions like AUTO_INCREMENT to equivalent expressions in other databases.

    This class is typically used when migrating databases or working with systems that need to support multiple database engines.

Properties

1. dbToSqlite

Declaration

private array $dbToSqlite;

Description

Array mapping of database field types to SQLite data types.

2. dbToMySQL

Declaration

private array $dbToMySQL;

Description

Array mapping of database field types to MySQL data types.

3. dbToPostgreSQL

Declaration

private array $dbToPostgreSQL;

Description

Array mapping of database field types to PostgreSQL data types.

Methods

2. replaceAll

Declaration

private function replaceAll(
    string|null $str,
    string $search,
    string $replacement
) : string|null
{
}

Description

Replaces all occurrences of a substring in the given string.

This function uses a regular expression to replace all matches of the search pattern with the specified replacement.

Parameters

$str

The string to search and replace in. If null, returns null.

$search

The substring to search for.

$replacement

The substring to replace the search pattern with.

Return

string|null

The modified string, or null if the input string is null.

3. translate

Declaration

public function translate(
    string $value,
    string $targetType
) : string
{
}

Description

Translates the provided SQL query to a specified target database format.

This method converts the provided SQL string into a format compatible with the specified target database (MySQL, PostgreSQL, or SQLite), ensuring that all relevant data types and structures are adapted.

Parameters

$value

The SQL query to be translated.

$targetType

The target database type ('mysql', 'pgsql', 'sqlite').

Return

string

The translated SQL query in the target database format.

4. convertQuery

Declaration

private function convertQuery(
    array $table,
    string $targetType
) : string
{
}

Description

Converts a table schema to a query compatible with the specified database type.

This method takes the parsed table schema and converts it to the corresponding SQL syntax for the target database.

Parameters

$table

The table schema to convert.

$targetType

The target database type ('mysql', 'pgsql', 'sqlite').

Return

string

The converted table schema in the target database format.

5. toSqliteOut

Declaration

private function toSqliteOut(
    array $table,
    string $targetType
) : string
{
}

Description

Converts a table schema to SQLite-specific SQL syntax.

This method adapts the provided table schema to SQLite format, including data type conversions and primary key handling.

Parameters

$table

The table schema to convert.

$targetType

The target database type ('sqlite').

Return

string

The converted table schema in SQLite format.

6. toMySQLOut

Declaration

private function toMySQLOut(
    array $table,
    string $targetType
) : string
{
}

Description

Converts a table schema to MySQL-specific SQL syntax.

This method adapts the provided table schema to MySQL format, including data type conversions and primary key handling.

Parameters

$table

The table schema to convert.

$targetType

The target database type ('mysql').

Return

string

The converted table schema in MySQL format.

7. toPostgreSQLOut

Declaration

private function toPostgreSQLOut(
    array $table,
    string $targetType
) : string
{
}

Description

Converts a table schema to PostgreSQL-specific SQL syntax.

This method adapts the provided table schema to PostgreSQL format, including data type conversions and primary key handling.

Parameters

$table

The table schema to convert.

$targetType

The target database type ('pgsql').

Return

string

The converted table schema in PostgreSQL format.

8. toSqliteTable

Declaration

private function toSqliteTable(
    string $sqliteTable,
    string $targetType
) : mixed
{
}

Description

Converts a given table for SQLite target type.

This method uses a common toTable function to convert a table for SQLite.

Parameters

$sqliteTable

The name of the SQLite table.

$targetType

The target database type (e.g., 'sqlite').

Return

mixed

The result of the toTable method.

9. toMySQLTable

Declaration

private function toMySQLTable(
    string $mysqlTable,
    string $targetType
) : mixed
{
}

Description

Converts a given table for MySQL target type.

This method uses a common toTable function to convert a table for MySQL.

Parameters

$mysqlTable

The name of the MySQL table.

$targetType

The target database type (e.g., 'mysql').

Return

mixed

The result of the toTable method.

10. toPostgreSQLTable

Declaration

private function toPostgreSQLTable(
    string $pgTable,
    string $targetType
) : mixed
{
}

Description

Converts a given table for PostgreSQL target type.

This method uses a common toTable function to convert a table for PostgreSQL.

Parameters

$pgTable

The name of the PostgreSQL table.

$targetType

The target database type (e.g., 'pgsql').

Return

mixed

The result of the toTable method.

11. isMySQL

Declaration

private function isMySQL(
    string $targetType
) : bool
{
}

Description

Checks if the target type is MySQL or MariaDB.

This method verifies if the target type matches MySQL or MariaDB.

Parameters

$targetType

The target database type.

Return

bool

Returns true if the target type is 'mysql' or 'mariadb', otherwise false.

12. isPGSQL

Declaration

private function isPGSQL(
    string $targetType
) : bool
{
}

Description

Checks if the target type is PostgreSQL.

This method verifies if the target type matches PostgreSQL or PGSQL.

Parameters

$targetType

The target database type.

Return

bool

Returns true if the target type is 'pgsql' or 'postgresql', otherwise false.

13. isSQLite

Declaration

private function isSQLite(
    string $targetType
) : bool
{
}

Description

Checks if the target type is SQLite.

This method verifies if the target type matches SQLite.

Parameters

$targetType

The target database type.

Return

bool

Returns true if the target type is 'sqlite', otherwise false.

14. isReal

Declaration

private function isReal(
    string $columnType
) : bool
{
}

Description

Checks if the given column type is a real number (e.g., FLOAT, DOUBLE, REAL, DECIMAL).

This method checks if the column type corresponds to a real number type.

Parameters

$columnType

The column type to check.

Return

bool

Returns true if the column type is a real number, otherwise false.

15. isBoolean

Declaration

private function isBoolean(
    string $columnType
) : bool
{
}

Description

Checks if the given column type is a boolean type (e.g., BOOLEAN, BOOL, TINYINT(1)).

This method checks if the column type corresponds to a boolean type.

Parameters

$columnType

The column type to check.

Return

bool

Returns true if the column type is boolean, otherwise false.

16. toSqliteType

Declaration

public function toSqliteType(
    string $type,
    int|null $length = null
) : string
{
}

Description

Converts a column type to the SQLite type format.

Parameters

$type

The original column type.

$length

The column length (optional).

Return

string

The converted SQLite column type.

17. toMySQLType

Declaration

public function toMySQLType(
    string $type,
    int|null $length = null
) : string
{
}

Description

Converts a column type to the MySQL type format.

Parameters

$type

The original column type.

$length

The column length (optional).

Return

string

The converted MySQL column type.

18. toPostgreSQLType

Declaration

public function toPostgreSQLType(
    string $type,
    int|null $length = null
) : string
{
}

Description

Converts a column type to the PostgreSQL type format.

Parameters

$type

The original column type.

$length

The column length (optional).

Return

string

The converted PostgreSQL column type.

19. parseEnumValue

Declaration

private function parseEnumValue(
    string $inputString
) : array
{
}

Description

Parses an ENUM type value and extracts the values in single quotes, also calculating the maximum length.

Parameters

$inputString

The ENUM values in a string format.

Return

array

An associative array containing the result array and maximum length of ENUM values.

20. parseNumericType

Declaration

private function parseNumericType(
    string $inputString
) : array
{
}

Description

Parses a numeric type value like DECIMAL(6,3), NUMERIC(10,2), etc.

Parameters

$inputString

The numeric value in string format, like 'DECIMAL(6, 3)'.

Return

array

An associative array containing the type (e.g., DECIMAL) and the length (total digits) and scale (digits after the decimal point).

21. toTable

Declaration

public function toTable(
    array $table,
    string $targetType
) : string
{
}

Description

Converts the table schema into a SQL CREATE TABLE statement for the specified database.

This method generates a SQL CREATE TABLE statement based on the provided table schema and target database type, adapting column definitions, default values, and other relevant attributes.

Parameters

$table

The table schema to convert.

$targetType

The target database type ('mysql', 'pgsql', 'sqlite').

Return

string

The SQL CREATE TABLE statement.

22. isTinyInt1

Declaration

public function isTinyInt1(
    string $type,
    int $length
) : bool
{
}

Description

Checks if the column type is TINYINT with a length of 1.

This method checks if the given column type is 'TINYINT' and if its length is exactly 1, which is commonly used to represent boolean values in certain databases.

Parameters

$type

The data type of the column (e.g., 'TINYINT').

$length

The length of the column (e.g., 1).

Return

bool

True if the type is 'TINYINT' and length is 1, otherwise false.

23. isInteger

Declaration

public function isInteger(
    string $type
) : bool
{
}

Description

Checks if the column type is an integer (e.g., TINYINT, SMALLINT, INT, BIGINT).

Parameters

$type

The column data type (e.g., 'INT', 'BIGINT').

Return

bool

True if the column type is an integer type, otherwise false.

24. isAutoIncrement

Declaration

public function isAutoIncrement(
    bool $autoIncrement,
    string $targetType
) : bool
{
}

Description

Determines if a column is auto-incremented for MySQL databases.

Parameters

$autoIncrement

Whether the column is set to auto-increment.

$targetType

The target database type (e.g., 'mysql', 'mariadb').

Return

bool

True if the column is auto-incremented in MySQL or MariaDB, otherwise false.

25. isNotEmpty

Declaration

public function isNotEmpty(
    string $value
) : bool
{
}

Description

Checks if a value is not empty (not null or an empty string).

Parameters

$value

The value to check.

Return

bool

True if the value is not empty, otherwise false.

26. hasDefaultValue

Declaration

public function hasDefaultValue(
    bool $primaryKey,
    string $defaultValue
) : bool
{
}

Description

Determines if a column has a default value, excluding primary keys.

Parameters

$primaryKey

Whether the column is a primary key.

$defaultValue

The default value of the column.

Return

bool

True if the column has a default value, otherwise false.

27. fixTableName

Declaration

public function fixTableName(
    string $tableName,
    string $targetType
) : string
{
}

Description

Fixes the table name according to the target database type.

This method adjusts the table name by removing any database prefix and applying the appropriate syntax for the target database (e.g., quoting for MySQL or PostgreSQL).

Parameters

$tableName

The name of the table to fix.

$targetType

The target database type (e.g., 'mysql', 'pgsql').

Return

string

The fixed table name.

28. fixColumnName

Declaration

public function fixColumnName(
    string $columnName,
    string $targetType
) : string
{
}

Description

Fixes the column name according to the target database type.

This method applies proper quoting for column names based on the target database (e.g., MySQL uses backticks for column names).

Parameters

$columnName

The name of the column to fix.

$targetType

The target database type (e.g., 'mysql').

Return

string

The fixed column name.

29. getDefaultData

Declaration

public function getDefaultData(
    string $defaultValue,
    string $columnType
) : string
{
}

Description

Generates the default value SQL for a column based on its type.

This method returns the appropriate default value syntax for the column's type, handling different types such as BOOLEAN, INTEGER, and REAL.

Parameters

$defaultValue

The default value to apply to the column.

$columnType

The type of the column (e.g., 'BOOLEAN', 'INT').

Return

string

The default value SQL definition for the column.

30. convertToBoolean

Declaration

public function convertToBoolean(
    mixed $value
) : string
{
}

Description

Converts a value to a boolean format.

Parameters

$value

The value to convert.

Return

string

The converted boolean value ('TRUE' or 'FALSE').

31. convertToInteger

Declaration

public function convertToInteger(
    mixed $value
) : int
{
}

Description

Converts a value to an integer format.

Parameters

$value

The value to convert.

Return

int

The converted integer value.

32. convertToReal

Declaration

public function convertToReal(
    mixed $value
) : float
{
}

Description

Converts a value to a real number format.

Parameters

$value

The value to convert.

Return

float

The converted real number value.

33. fixDefaultValue

Declaration

public function fixDefaultValue(
    string $defaultValue,
    string $targetType
) : string
{
}

Description

Fixes default value for SQLite.

Parameters

$defaultValue

The default value to fix.

$targetType

The target database type.

Return

string

The fixed default value.

34. addslashes

Declaration

public function addslashes(
    string $text
) : string
{
}

Description

Escapes special characters in a string for use in SQL statements.

This method wraps the PHP addslashes() function, which adds backslashes before characters that need to be escaped in SQL, such as quotes, backslashes, and NULL characters.

Parameters

$text

The input string to escape.

Return

string

The escaped string with special characters properly handled.

35. extractDropTableQueries

Declaration

public function extractDropTableQueries(
    string $sql,
    string $targetType
) : array
{
}

Description

Extracts the DROP TABLE IF EXISTS queries from the provided SQL string.

Parameters

$sql

The SQL string to be processed.

$targetType

The type of database ('pgsql', 'mysql', or 'mariadb') to format the table names accordingly.

Return

array

An array of objects, each containing the name of a table to be dropped.

36. extractTableName

Declaration

public function extractTableName(
    string $input
) : string
{
}

Description

Extracts the table name from the input string, removing schema if present.

Parameters

$input

The input string (may contain schema.table or just table).

Return

string

The extracted table name without schema.

MagicObject\Util\Database\PicoSqlParser

Declaration

class PicoSqlParser { }

Package

MagicObject\Util\Database

Links

  1. https://github.com/Planetbiru/ERD-Maker

Description

Class PicoSqlParser

This class parses SQL CREATE TABLE statements to extract table information such as:

  • Table name
  • Column names
  • Data types
  • Column attributes (nullable, default value, etc.)
  • Primary keys and other constraints

    This class is useful for generating database documentation, creating Entity Relationship Diagrams (ERDs), or analyzing database structures from SQL DDL scripts.

    Example usage:

    <?php
    $parser = new PicoSqlParser($sql);
    $result = $parser->getResult();

Constants

const KEY_COLUMN_NAME = "Field";
const KEY_PRIMARY_KEY = "Key";
const KEY_TYPE = "Type";
const KEY_LENGTH = "Length";
const KEY_NULLABLE = "Nullable";
const KEY_DEFAULT = "Default";

Properties

1. typeList

Declaration

private array $typeList = array();

Description

List of valid SQL data types supported by this parser.

2. tableInfo

Declaration

private array $tableInfo = array();

Description

Information about the parsed tables, including columns, data types, and primary keys.

Methods

1. __construct

Declaration

public function __construct(
    string|null $sql = null
)
{
}

Description

Constructor to initialize the parser. Optionally parses an SQL statement immediately upon instantiation.

Parameters

$sql

The SQL statement to parse (optional).

2. inArray

Declaration

private function inArray(
    array $haystack,
    mixed $needle
) : bool
{
}

Description

Checks if a specific element exists in the array.

Parameters

$haystack

Array to search in.

$needle

Element to search for.

Return

bool

True if the element is found, false otherwise.

3. parseTable

Declaration

public function parseTable(
    string $sql
) : array
{
}

Description

Parses a CREATE TABLE statement to extract table information.

Parameters

$sql

SQL statement to be parsed.

Return

array

Information about the table, columns, and primary key.

Throws

InvalidArgumentException

if the SQL statement is not a valid CREATE TABLE statement.

4. getLength

Declaration

private function getLength(
    string $text
) : string|null
{
}

Description

Extracts the length of a data type if it is defined in the SQL (e.g., VARCHAR(100)).

Parameters

$text

The data type definition, e.g., VARCHAR(100).

Return

string|null

Returns the length if defined (e.g., 100 for VARCHAR(100)), or null if not.

5. isValidType

Declaration

private function isValidType(
    string $dataType
) : bool
{
}

Description

Validates whether the provided data type is in the list of supported types.

Parameters

$dataType

The data type to check (e.g., int, varchar).

Return

bool

Returns true if the data type is valid, false otherwise.

6. getResult

Declaration

public function getResult() : array
{
}

Description

Returns the result of the most recent table parsing.

Return

array

The parsed table information (name, columns, primary keys).

7. init

Declaration

public function init() : void
{
}

Description

Initializes the list of valid SQL data types supported by the parser.

This method sets the list of data types that the parser recognizes, such as varchar, int, timestamp, boolean, json, uuid, etc. These data types correspond to common column types in various SQL-based databases like PostgreSQL, MySQL, and SQLite. The list may be used to validate or process SQL statements when parsing or generating SQL.

Return

void
8. parseAll

Declaration

public function parseAll(
    string $sql
) : array
{
}

Description

Parses all CREATE TABLE statements in the provided SQL text.

Parameters

$sql

The SQL statements to parse (can contain multiple CREATE TABLE statements).

Return

array

An array of parsed tables with their columns and primary keys.

9. getTypeList

Declaration

public function getTypeList() : array
{
}

Description

Returns the list of valid SQL data types that the parser recognizes.

Return

array

An array of valid SQL data types.

10. getTableInfo

Declaration

public function getTableInfo() : array
{
}

Description

Retrieves information about all the tables parsed.

Return

array

An array containing parsed information for all tables.

MagicObject\Util\Database\PicoTableParser

Declaration

class PicoTableParser { }

Package

MagicObject\Util\Database

Description

The PicoTableParser class is responsible for parsing SQL CREATE TABLE statements to extract table and column information. It validates data types, handles constraints like primary keys and auto-increment fields, and processes table comments and default values. This class can handle multiple SQL statements, parsing them into individual queries, and extracting structured information about the database schema from SQL scripts.

The class supports parsing complex SQL table definitions, including field types, constraints (e.g., primary keys, auto-increments), and special data types (e.g., ENUM, SET, JSON). Additionally, it provides methods to normalize and format SQL defaults, handle multi-line SQL statements, and retrieve detailed schema information for each parsed table.

Example usage: $parser = new PicoTableParser($sql); $tableInfo = $parser->getResult();

The returned result contains structured information about each table, including columns, their types, constraints, and additional attributes.

Properties

1. typeList

Declaration

private array $typeList = array();

Description

List of valid SQL data types used for column validation.

2. tableInfo

Declaration

private array $tableInfo = array();

Description

Holds information about the parsed tables, including columns and their properties.

Methods

1. __construct

Declaration

public function __construct(
    string|null $sql = null
)
{
}

Description

PicoTableParser constructor.

Initializes the PicoTableParser instance and optionally parses an SQL string.

Parameters

$sql

Optional SQL string to parse during initialization.

2. init

Declaration

private function init()
{
}

Description

Initializes the type list for valid SQL column types.

This function sets up an array of valid SQL column types, which will be used to validate column data types during parsing.

3. inArray

Declaration

private function inArray(
    array $haystack,
    string $needle
) : bool
{
}

Description

Checks if a value exists in an array.

Parameters

$haystack

The array to search.

$needle

The value to search for.

Return

bool

Returns true if the needle is found in the haystack, otherwise false.

4. isPrimaryKey

Declaration

private function isPrimaryKey(
    string $field
) : bool
{
}

Description

Checks if a field is a primary key.

Parameters

$field

The field definition.

Return

bool

True if the field is a primary key, otherwise false.

5. isAutoIncrement

Declaration

private function isAutoIncrement(
    string $line
) : bool
{
}

Description

Checks if a field is auto-incremented.

Parameters

$line

The field definition.

Return

bool

True if the field is auto-incremented, otherwise false.

6. parseTable

Declaration

public function parseTable(
    string $sql
) : array
{
}

Description

Parses a CREATE TABLE SQL statement and extracts table and column information.

Parameters

$sql

The SQL string representing a CREATE TABLE statement.

Return

array

An array containing table name, columns, and primary key information.

7. fixDefaultValue

Declaration

private function fixDefaultValue(
    string $defaultValue
) : string|null
{
}

Description

Fixes and normalizes default values in SQL statements.

Parameters

$defaultValue

The raw default value from SQL.

Return

string|null

The normalized default value or null if empty.

8. isValidType

Declaration

private function isValidType(
    string $type
) : bool
{
}

Description

Validates if a type is one of the known types.

Parameters

$type

The data type to validate.

Return

bool

True if the type is valid, otherwise false.

9. getLength

Declaration

private function getLength(
    string $attr
) : int|null
{
}

Description

Extracts the length for types that require it, such as varchar.

Parameters

$attr

The attributes of the field.

Return

int|null

The length of the field or null if not applicable.

10. parseAll

Declaration

public function parseAll(
    string $sql
)
{
}

Description

Parses multiple SQL statements.

Parameters

$sql

The SQL statements.

11. parseSQL

Declaration

public function parseSQL(
    string $sqlText
) : array
{
}

Description

Parses a SQL text, splits it into individual SQL queries, and processes them by handling delimiters, comments, and empty lines. It returns an array of queries, each with its delimiter.

This method processes the SQL text by:

  1. Normalizing newlines.
  2. Removing comment lines and empty lines.
  3. Splitting the SQL text into queries based on the delimiter.
  4. Handling multiple queries that may span across multiple lines.
  5. Changing the delimiter if a new one is specified within the SQL text.

Parameters

$sqlText

The input SQL text to be parsed.

Return

array

An array of queries, each containing the SQL query string and its corresponding delimiter.

12. getTableInfo

Declaration

public function getTableInfo() : array
{
}

Description

Returns the table information parsed from the SQL statements.

Return

array

An array of parsed table information.

13. getResult

Declaration

public function getResult() : array
{
}

Description

Get the value of tableInfo.

Return

array

The table information.

MagicObject\Util\Database\PicoTimeZoneChanger

Declaration

class PicoTimeZoneChanger { }

Methods

1. changeTimeZone

Declaration

public static function changeTimeZone(
    string|DateTime|int $datetime,
    string|DateTimeZone $from,
    string|DateTimeZone $to
) : string|DateTime|int
{
}

Description

Changes the time from the source timezone to the target timezone, only if the timezones are different.

Parameters

$datetime

The time in string format, DateTime object, or Unix timestamp (integer).

$from

The source timezone (string or DateTimeZone object).

$to

The target timezone (string or DateTimeZone object).

Return

string|DateTime|int

The time adjusted to the target timezone, in the same format as the input.

2. changeTimeZoneBeforeSave

Declaration

public static function changeTimeZoneBeforeSave(
    string|DateTime|int $datetime,
    PicoDatabase $database
) : string|DateTime|int
{
}

Description

Adjusts the given time according to the timezone settings from the database configuration before saving to the database. The time is adjusted only if the database driver is either "sqlsrv" or "sqlite", and the source and target timezones are different.

This method is useful for ensuring that the time is correctly adjusted before being saved to the database, based on the application's time zone and the database's time zone settings.

Parameters

$datetime

The time to be adjusted. Can be a string, DateTime object, or Unix timestamp (integer).

$database

The database object containing the database configuration with timezones.

Return

string|DateTime|int

The time adjusted to the target timezone, or the original datetime if no conversion is needed.

3. changeTimeZoneAfterRead

Declaration

public static function changeTimeZoneAfterRead(
    string|DateTime|int $datetime,
    PicoDatabase $database
) : string|DateTime|int
{
}

Description

Reverses the time zone conversion after reading data from the database. This function is useful for converting the time from the target timezone back to the original source timezone after the data has been fetched from the database. The time is adjusted only if the database driver is either "sqlsrv" or "sqlite", and the source and target timezones are different.

This method ensures that the time is returned to the correct timezone as per the application's settings, after being retrieved from the database.

Parameters

$datetime

The time to be adjusted. Can be a string, DateTime object, or Unix timestamp (integer).

$database

The database object containing the database configuration with timezones.

Return

string|DateTime|int

The time adjusted to the source timezone, or the original datetime if no conversion is needed.

MagicObject\Util\Dms

Declaration

class Dms { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class Dms

This class provides methods to convert between Decimal Degrees and Degrees/Minutes/Seconds (DMS) formats. It also allows printing of these representations in a specified format.

Properties

1. deg

Declaration

private int $deg = 0;

Description

Degree component.

2. min

Declaration

private int $min = 0;

Description

Minute component.

3. sec

Declaration

private float $sec = 0.0;

Description

Second component.

4. dd

Declaration

private float $dd = 0.0;

Description

Decimal degree value.

Methods

1. dmsToDd

Declaration

public function dmsToDd(
    int $deg,
    int $min,
    float $sec
) : self
{
}

Description

Converts DMS (Degrees/Minutes/Seconds) to decimal format.

This method takes degree, minute, and second components and converts them to a decimal degree value.

Example:

 <?php
 $dms = new Dms();
 $dms->dmsToDd(34, 15, 30);
 echo $dms->printDd(); // Outputs: 34.258333

Parameters

$deg

Degree component.

$min

Minute component.

$sec

Second component.

Return

self

Returns the current instance for method chaining.

2. ddToDms

Declaration

public function ddToDms(
    float $dec
) : self
{
}

Description

Converts decimal format to DMS (Degrees/Minutes/Seconds).

This method takes a decimal degree value and converts it to its DMS representation, storing the results in the instance variables.

Example:

 <?php
 $dms = new Dms();
 $dms->ddToDms(34.258333);
 echo $dms->printDms(); // Outputs: 34:15:30

Parameters

$dec

Decimal degree value.

Return

self

Returns the current instance for method chaining.

3. printDms

Declaration

public function printDms(
    bool $trim = false,
    bool $rounded = false
) : string
{
}

Description

Prints the DMS (Degrees/Minutes/Seconds) representation.

This method outputs the DMS format as a string.

Parameters

$trim

Flag to indicate whether to trim leading zeros.

$rounded

Flag to indicate whether to round the seconds.

Return

string

The DMS representation in "deg:min:sec" format.

4. printDd

Declaration

public function printDd() : string
{
}

Description

Prints the decimal degree representation.

This method outputs the decimal degree format as a string.

Return

string

The decimal degree representation.

MagicObject\Util\File\FileUtil

Declaration

class FileUtil { }

Package

MagicObject\Util\File

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class FileUtil

A utility class for handling file operations such as retrieving files from a directory and fixing file paths. This class cannot be instantiated due to its private constructor.

Methods

2. getFiles

Declaration

public static function getFiles(
    string $directory,
    int $level = 0,
    string|null $origin = null
) : array
{
}

Description

Retrieves all files from a given directory, optionally at specified levels of depth. Returns the file paths relative to the original directory if a level greater than 0 is specified.

Parameters

$directory

The directory to scan for files.

$level

The depth level for recursive scanning (default is 0).

$origin

The origin directory for relative path calculation.

Return

array

An array of file paths found within the specified directory.

3. fixFilePath

Declaration

public static function fixFilePath(
    string $filePath
) : string
{
}

Description

Normalizes the file path by replacing any backslashes or forward slashes with the correct directory separator for the current platform.

Parameters

$filePath

The file path to be normalized.

Return

string

The normalized file path.

MagicObject\Util\Image\ImageColor

Declaration

class ImageColor { }

Package

MagicObject\Util\Image

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class ImageColor

Represents an RGB color and provides methods for manipulating and retrieving color information in various formats (hexadecimal, RGB). This class can also allocate the color to a given GD image resource for rendering.

Properties

1. red

Declaration

protected int $red;

Description

Red component

2. green

Declaration

protected int $green;

Description

Green component

3. blue

Declaration

protected int $blue;

Description

Blue component

Methods

1. __construct

Declaration

public function __construct(
    int $red,
    int $green,
    int $blue
)
{
}

Description

Constructor

Parameters

$red

Red component

$green

Green component

$blue

Blue component

2. allocate

Declaration

public function allocate(
    GdImage $image
) : int
{
}

Description

Allocate color in the given image resource.

Parameters

$image

The GD image resource.

Return

int

The color index of the allocated color.

3. getHex

Declaration

public function getHex() : string
{
}

Description

Get color in hexadecimal format.

Return

string

The color represented as a hexadecimal string.

4. getRgb

Declaration

public function getRgb() : string
{
}

Description

Get color in RGB format.

Return

string

The color represented as an RGB string.

5. getRed

Declaration

public function getRed() : int
{
}

Description

Get the red component of the color.

Return

int

The red component.

6. setRed

Declaration

public function setRed(
    int $red
) : self
{
}

Description

Set the red component of the color.

Parameters

$red

The red component.

Return

self

Returns the current instance for method chaining.

7. getGreen

Declaration

public function getGreen() : int
{
}

Description

Get the green component of the color.

Return

int

The green component.

8. setGreen

Declaration

public function setGreen(
    int $green
) : self
{
}

Description

Set the green component of the color.

Parameters

$green

The green component.

Return

self

Returns the current instance for method chaining.

9. getBlue

Declaration

public function getBlue() : int
{
}

Description

Get the blue component of the color.

Return

int

The blue component.

10. setBlue

Declaration

public function setBlue(
    int $blue
) : self
{
}

Description

Set the blue component of the color.

Parameters

$blue

The blue component.

Return

self

Returns the current instance for method chaining.

MagicObject\Util\Image\ImageColorAlpha

Declaration

class ImageColorAlpha extends MagicObject\Util\Image\ImageColor { }

Package

MagicObject\Util\Image

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class ImageColorAlpha

Represents a color with an alpha channel for transparency in images.

Example:

 <?php
 $color = new ImageColorAlpha(255, 0, 0, 50); // Red with 50% opacity

Properties

1. alpha

Declaration

protected int $alpha;

Description

The alpha value for the color (0 is fully opaque, 127 is fully transparent).

2. red

Declaration

protected int $red;

Description

Red component

3. green

Declaration

protected int $green;

Description

Green component

4. blue

Declaration

protected int $blue;

Description

Blue component

Methods

3. getAlpha

Declaration

public function getAlpha() : int
{
}

Description

Gets the alpha value of the color.

Return

int

The alpha value (0-127).

4. getRgba

Declaration

public function getRgba() : string
{
}

Description

Gets the RGBA representation of the color as a string.

Return

string

The color in rgba format.

MagicObject\Util\Image\ImageExif

Declaration

class ImageExif { }

Description

Class ImageExif

Provides functionality to extract and process EXIF data from images, particularly GPS coordinates. This class reads the EXIF metadata from an image file and retrieves the latitude and longitude, converting them from degrees, minutes, seconds (DMS) format to decimal format.

Methods

1. getLatLongFromImage

Declaration

public function getLatLongFromImage(
    string $imagePath
) : array|null
{
}

Description

Retrieves latitude and longitude from the EXIF data of an image.

This method checks if the image file exists, reads its EXIF data, and extracts the GPS coordinates (latitude and longitude) if available. The coordinates are returned in decimal format.

Parameters

$imagePath

The path to the image file.

Return

array|null

An array containing the latitude and longitude in decimal format, or null if GPS data is not available.

ImageResize

Declaration

class ImageResize { }

Methods

1. resizeImage

Declaration

public function resizeImage(
    string $sourcePath,
    string $destPath,
    int $maxWidth,
    int $maxHeight
) : void
{
}

Description

Resize an image while maintaining the aspect ratio.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the resized image.

$maxWidth

Maximum width of the resized image.

$maxHeight

Maximum height of the resized image.

Return

void
2. resizeCropCenter

Declaration

public function resizeCropCenter(
    string $sourcePath,
    string $destPath,
    int $targetWidth,
    int $targetHeight
) : void
{
}

Description

Resize and crop the image from the center while maintaining the aspect ratio.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the resized image.

$targetWidth

Target width of the cropped image.

$targetHeight

Target height of the cropped image.

Return

void
3. resizePaddingCenter

Declaration

public function resizePaddingCenter(
    string $sourcePath,
    string $destPath,
    int $targetWidth,
    int $targetHeight
) : void
{
}

Description

Resize and add padding to the image from the center while maintaining the aspect ratio.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the resized image.

$targetWidth

Target width of the final image.

$targetHeight

Target height of the final image.

Return

void
4. resizeCropTopLeft

Declaration

public function resizeCropTopLeft(
    string $sourcePath,
    string $destPath,
    int $targetWidth,
    int $targetHeight
) : void
{
}

Description

Resize and crop the image from the top left while maintaining the aspect ratio.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the resized image.

$targetWidth

Target width of the cropped image.

$targetHeight

Target height of the cropped image.

Return

void
5. resizePaddingTopRight

Declaration

public function resizePaddingTopRight(
    string $sourcePath,
    string $destPath,
    int $targetWidth,
    int $targetHeight
) : void
{
}

Description

Resize and add padding to the image from the top right while maintaining the aspect ratio.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the resized image.

$targetWidth

Target width of the final image.

$targetHeight

Target height of the final image.

Return

void
6. resizeCropTopRight

Declaration

public function resizeCropTopRight(
    string $sourcePath,
    string $destPath,
    int $targetWidth,
    int $targetHeight
) : void
{
}

Description

Resize and crop the image from the top right while maintaining the aspect ratio.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the resized image.

$targetWidth

Target width of the cropped image.

$targetHeight

Target height of the cropped image.

Return

void
7. resizeCropBottomLeft

Declaration

public function resizeCropBottomLeft(
    string $sourcePath,
    string $destPath,
    int $targetWidth,
    int $targetHeight
) : void
{
}

Description

Resize and crop the image from the bottom left while maintaining the aspect ratio.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the resized image.

$targetWidth

Target width of the cropped image.

$targetHeight

Target height of the cropped image.

Return

void
8. resizeCropBottomRight

Declaration

public function resizeCropBottomRight(
    string $sourcePath,
    string $destPath,
    int $targetWidth,
    int $targetHeight
) : void
{
}

Description

Resize and crop the image from the bottom right while maintaining the aspect ratio.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the resized image.

$targetWidth

Target width of the cropped image.

$targetHeight

Target height of the cropped image.

Return

void
9. flipVertical

Declaration

public function flipVertical(
    string $sourcePath,
    string $destPath
) : void
{
}

Description

Flip the image vertically.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the flipped image.

Return

void
10. flipHorizontal

Declaration

public function flipHorizontal(
    string $sourcePath,
    string $destPath
) : void
{
}

Description

Flip the image horizontally.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the flipped image.

Return

void
11. rotate90

Declaration

public function rotate90(
    string $sourcePath,
    string $destPath
) : void
{
}

Description

Rotate the image by 90 degrees clockwise.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the rotated image.

Return

void
12. rotate180

Declaration

public function rotate180(
    string $sourcePath,
    string $destPath
) : void
{
}

Description

Rotate the image by 180 degrees.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the rotated image.

Return

void
13. rotate270

Declaration

public function rotate270(
    string $sourcePath,
    string $destPath
) : void
{
}

Description

Rotate the image by 270 degrees clockwise.

Parameters

$sourcePath

Path to the source image.

$destPath

Path to save the rotated image.

Return

void
14. addWatermark

Declaration

public function addWatermark(
    string $sourcePath,
    string $watermarkPath,
    string $outputPath,
    int $opacity = 50,
    string $position = 'bottom-right',
    int $marginX = 10,
    int $marginY = 10
) : bool
{
}

Description

Adds a watermark to an image.

Parameters

$sourcePath

Path to the source image.

$watermarkPath

Path to the watermark image.

$outputPath

Path to save the resulting image.

$opacity

Opacity of the watermark (0-100).

$position

Position of the watermark (top-left, top-right, bottom-left, bottom-right, center).

$marginX

Horizontal margin from the edge.

$marginY

Vertical margin from the edge.

Return

bool

True on success, false on failure.

MagicObject\Util\Image\ImageUtil

Declaration

class ImageUtil { }

Package

MagicObject\Util\Image

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class ImageUtil

A wrapper for the GD library in PHP. GD must be installed in your system for this to work.

Example:

 <?php
 $img = new Image('wheel.png');
 $img->flip(1)->resize(120, 0)->save('wheel.jpg');

Constants

const FLIP_HORIZONTAL = 1;
const FLIP_VERTICAL = 2;
const FLIP_BOTH = 3;
const STAMP_POSITION_TOPRIGHT = 1;
const STAMP_POSITION_TOPLEFT = 2;
const STAMP_POSITION_BOTTOMRIGHT = 3;
const STAMP_POSITION_BOTTOMLEFT = 4;
const STAMP_POSITION_CENTER = 5;
const STAMP_POSITION_TOP = 6;
const STAMP_POSITION_BOTTOM = 7;
const STAMP_POSITION_LEFT = 8;
const STAMP_POSITION_RIGHT = 9;
const STAMP_POSITION_RANDOM = 999;
const TEXT_ALIGN_LEFT = 1;
const TEXT_ALIGN_RIGHT = 2;
const TEXT_ALIGN_CENTER = 3;

Properties

3. image

Declaration

private GdImage $image;

Description

Image

4. orgImage

Declaration

private GdImage $orgImage;

Description

Image

5. width

Declaration

protected integer $width;

Description

Image width

6. height

Declaration

protected integer $height;

Description

Image height

Methods

1. empty

Declaration

public static function empty(
    int $width,
    int $height,
    ImageColor|null $color = null
) : self
{
}

Description

Creates an empty image with specified dimensions and color.

Parameters

$width

The width of the new image.

$height

The height of the new image.

$color

Optional color to fill the image.

Return

self

Returns the current instance for method chaining.

2. __construct

Declaration

public function __construct(
    string|resource $imageFile
)
{
}

Description

Constructs an ImageUtil instance based on an image resource or file name.

Parameters

$imageFile

The path or URL to the image, or the image resource.

Throws

ImageUtilException

If the GD module is not installed or if the image file is invalid.

FileNotFoundException

If the image file is not found or not readable.

3. createFromResource

Declaration

protected function createFromResource(
    resource $resource
) : array
{
}

Description

Creates an ImageUtil instance from a resource.

Parameters

$resource

The image resource.

Return

array

Information about the image.

Throws

ImageUtilException

If the resource is invalid.

4. createFromFilename

Declaration

protected function createFromFilename(
    string $imageFile
) : array
{
}

Description

Creates an ImageUtil instance from a file name.

Parameters

$imageFile

The path to the image file.

Return

array

Information about the image.

Throws

FileNotFoundException

If the file is not found or not readable.

ImageUtilException

If the file is invalid.

5. getWidth

Declaration

public function getWidth() : int
{
}

Description

Get the image width.

Return

int
6. getHeight

Declaration

public function getHeight() : int
{
}

Description

Get the image height.

Return

int
7. getFilename

Declaration

public function getFilename() : string
{
}

Description

Get the file name of the image.

Return

string
8. retainTransparency

Declaration

protected function retainTransparency(
    GdImage|null $image = null
) : void
{
}

Description

Retain transparency for the image.

Parameters

$image

The image resource to modify.

Return

void
9. getImage

Declaration

public function getImage() : GdImage
{
}

Description

Get the current image resource.

Return

GdImage
10. rotate

Declaration

public function rotate(
    float $angle,
    int $background = 0
) : $this
{
}

Description

Rotates the image to any direction using the given angle.

Parameters

$angle

The rotation angle, in degrees.

$background

The background color for the rotated area.

Return

$this

Throws

InvalidParameterException

If the angle is not numeric.

11. flip

Declaration

public function flip(
    int $type
) : ImageUtil
{
}

Description

Mirrors the given image in the desired way.

Parameters

$type

Direction of mirroring (1: Horizontal, 2: Vertical, 3: Both).

Return

ImageUtil

Throws

InvalidParameterException

If the flip type is invalid.

12. resize

Declaration

public function resize(
    int|null $newWidth = null,
    int|null $newHeight = null
) : ImageUtil
{
}

Description

Resize the image to a new size.

Parameters

$newWidth

The new width of the image.

$newHeight

The new height of the image.

Return

ImageUtil

Throws

InvalidParameterException

If neither width nor height is valid.

13. resizeSquare

Declaration

public function resizeSquare(
    int $newSize,
    ImageColor|null $color = null
) : ImageUtil
{
}

Description

Resize the image in a square format and maintain the aspect ratio.

Parameters

$newSize

The new size of the image (width and height are equal).

$color

Optional color to fill the extra space.

Return

ImageUtil

Throws

ImageUtilException

If an error occurs during resizing.

14. resizeAspectRatio

Declaration

public function resizeAspectRatio(
    int $newX,
    int $newY,
    ImageColor|null $color = null
) : self
{
}

Description

Resizes the image while maintaining the aspect ratio.

Parameters

$newX

The new width.

$newY

The new height.

$color

Optional color to fill the extra space.

Return

self

Returns the current instance for method chaining.

Throws

ImageUtilException

If an error occurs during resizing.

15. stampImage

Declaration

public function stampImage(
    ImageUtil|string $srcImage,
    int $position = 3,
    int $padding = 5,
    int $opacity
) : self
{
}

Description

Stamps an image onto the current image.

Parameters

$srcImage

The image path or ImageUtil instance.

$position

The position where the stamp will be placed.

$padding

The padding between the stamp and the edges.

$opacity

The opacity of the stamp (0-100).

Return

self

Returns the current instance for method chaining.

Throws

ImageUtilException

If an error occurs during stamping.

FileNotFoundException

If the source image is not found.

16. writeText

Declaration

public function writeText(
    string $text,
    float[] $point,
    float $size,
    float $angle,
    string $font,
    int $maxwidth = 0,
    float[]|null $rgbAr = null,
    int $textAlignment = 1
)
{
}

Description

Writes text on the image.

Parameters

$text

The text to write.

$point

The coordinates to place the text (x, y).

$size

The font size.

$angle

The angle of the text.

$font

The path to the font file.

$maxwidth

The maximum width of the text.

$rgbAr

RGB array for text color.

$textAlignment

The alignment of the text (left, center, right).

Throws

ImageUtilException

If the specified font is not found or if an error occurs.

17. crop

Declaration

public function crop(
    float $fromX,
    float $fromY,
    float $toX,
    float $toY
) : self
{
}

Description

Crops the image from specified coordinates.

Parameters

$fromX

The starting X coordinate.

$fromY

The starting Y coordinate.

$toX

The ending X coordinate.

$toY

The ending Y coordinate.

Return

self

Returns the current instance for method chaining.

18. restore

Declaration

public function restore() : self
{
}

Description

Discards changes and restores the original image state.

Return

self

Returns the current instance for method chaining.

19. makeTransparent

Declaration

public function makeTransparent(
    ImageColor|null $color = null,
    GdImage|null $image = null
) : $this|GdImage
{
}

Description

Makes a color transparent in the image.

Parameters

$color

The color to make transparent.

$image

The image resource to modify. If null, uses the current image.

Return

$this|GdImage

The modified image or the current instance.

20. __destruct

Declaration

public function __destruct()
{
}

Description

Destroy the image to save the memory. Do this after all operations are complete.

MagicObject\Util\Image\ImageUtilException

Declaration

class ImageUtilException extends Exception implements Throwable { }

Package

MagicObject\Util\Image

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class ImageUtilException

Custom exception class for handling image-related errors in the MagicObject library.

Example:

 <?php
 throw new ImageUtilException("Error processing image", 500);

Properties

1. previous

Declaration

private Throwable $previous;

Description

Previous exception

MagicObject\Util\Parsedown

Declaration

class Parsedown { }

Description

Parsedown http://parsedown.org

(c) Emanuil Rusev http://erusev.com

For the full license information, view the LICENSE file that was distributed with this source code.

Constants

const VERSION = "1.7.4";

Properties

1. breaksEnabled

Declaration

protected bool $breaksEnabled;

Description

Flag indicating whether to enable line breaks in the parsed output.

2. markupEscaped

Declaration

protected bool $markupEscaped;

Description

Flag indicating whether to escape HTML markup in the parsed output.

3. urlsLinked

Declaration

protected bool $urlsLinked = true;

Description

Flag indicating whether to automatically link URLs in the parsed output.

4. safeMode

Declaration

protected bool $safeMode;

Description

Flag indicating whether to enable safe mode for handling links.

5. safeLinksWhitelist

Declaration

protected array $safeLinksWhitelist = array ( 0 => 'http://', 1 => 'https://', 2 => 'ftp://', 3 => 'ftps://', 4 => 'mailto:', 5 => 'data:image/png;base64,', 6 => 'data:image/gif;base64,', 7 => 'data:image/jpeg;base64,', 8 => 'irc:', 9 => 'ircs:', 10 => 'git:', 11 => 'ssh:', 12 => 'news:', 13 => 'steam:', );

Description

List of allowed protocols for safe mode links.

6. blockTypes

Declaration

protected array $blockTypes = array ( '#' => array ( 0 => 'Header', ), '*' => array ( 0 => 'Rule', 1 => 'List', ), '+' => array ( 0 => 'List', ), '-' => array ( 0 => 'SetextHeader', 1 => 'Table', 2 => 'Rule', 3 => 'List', ), 0 => array ( 0 => 'List', ), 1 => array ( 0 => 'List', ), 2 => array ( 0 => 'List', ), 3 => array ( 0 => 'List', ), 4 => array ( 0 => 'List', ), 5 => array ( 0 => 'List', ), 6 => array ( 0 => 'List', ), 7 => array ( 0 => 'List', ), 8 => array ( 0 => 'List', ), 9 => array ( 0 => 'List', ), ':' => array ( 0 => 'Table', ), '<' => array ( 0 => 'Comment', 1 => 'Markup', ), '=' => array ( 0 => 'SetextHeader', ), '>' => array ( 0 => 'Quote', ), '[' => array ( 0 => 'Reference', ), '_' => array ( 0 => 'Rule', ), '`' => array ( 0 => 'FencedCode', ), '|' => array ( 0 => 'Table', ), '~' => array ( 0 => 'FencedCode', ), );

Description

Array mapping block markers to their respective types.

7. unmarkedBlockTypes

Declaration

protected array $unmarkedBlockTypes = array ( 0 => 'Code', );

Description

List of block types that are unmarked.

8. inlineTypes

Declaration

protected $inlineTypes = array ( '"' => array ( 0 => 'SpecialCharacter', ), '!' => array ( 0 => 'Image', ), '&' => array ( 0 => 'SpecialCharacter', ), '*' => array ( 0 => 'Emphasis', ), ':' => array ( 0 => 'Url', ), '<' => array ( 0 => 'UrlTag', 1 => 'EmailTag', 2 => 'Markup', 3 => 'SpecialCharacter', ), '>' => array ( 0 => 'SpecialCharacter', ), '[' => array ( 0 => 'Link', ), '_' => array ( 0 => 'Emphasis', ), '`' => array ( 0 => 'Code', ), '~' => array ( 0 => 'Strikethrough', ), '\\' => array ( 0 => 'EscapeSequence', ), );

Description

Process inline elements within a line of text.

This method identifies and constructs inline elements based on their markers.

Parameters

$text

The line of text to process.

$nonNestables

An array of non-nestable inline types.

Return

string

The processed markup with inline elements.

10. instances

Declaration

private $instances = array();

Description

@var array Holds instances of the class.

11. definitionData

Declaration

protected $definitionData;

Description

@var mixed Contains the definition data for reference links.

12. specialCharacters

Declaration

protected $specialCharacters = array ( 0 => '\\', 1 => '`', 2 => '*', 3 => '_', 4 => '{', 5 => '}', 6 => '[', 7 => ']', 8 => '(', 9 => ')', 10 => '>', 11 => '#', 12 => '+', 13 => '-', 14 => '.', 15 => '!', 16 => '|', );

Description

@var array List of special characters used in parsing.

13. strongRegex

Declaration

protected $strongRegex = array ( '*' => '/^[*]{2}((?:\\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s', '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us', );

Description

@var array Regular expressions for strong emphasis syntax.

14. emRegex

Declaration

protected $emRegex = array ( '*' => '/^[*]((?:\\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\\b/us', );

Description

@var array Regular expressions for emphasis syntax.

15. regexHtmlAttribute

Declaration

protected $regexHtmlAttribute = '[a-zA-Z_:][\\w:.-]*(?:\\s*=\\s*(?:[^"\'=<>`\\s]+|"[^"]*"|\'[^\']*\'))?';

Description

@var string Regular expression for validating HTML attributes.

16. voidElements

Declaration

protected $voidElements = array ( 0 => 'area', 1 => 'base', 2 => 'br', 3 => 'col', 4 => 'command', 5 => 'embed', 6 => 'hr', 7 => 'img', 8 => 'input', 9 => 'link', 10 => 'meta', 11 => 'param', 12 => 'source', );

Description

@var array List of void elements that do not have closing tags.

17. textLevelElements

Declaration

protected $textLevelElements = array ( 0 => 'a', 1 => 'br', 2 => 'bdo', 3 => 'abbr', 4 => 'blink', 5 => 'nextid', 6 => 'acronym', 7 => 'basefont', 8 => 'b', 9 => 'em', 10 => 'big', 11 => 'cite', 12 => 'small', 13 => 'spacer', 14 => 'listing', 15 => 'i', 16 => 'rp', 17 => 'del', 18 => 'code', 19 => 'strike', 20 => 'marquee', 21 => 'q', 22 => 'rt', 23 => 'ins', 24 => 'font', 25 => 'strong', 26 => 's', 27 => 'tt', 28 => 'kbd', 29 => 'mark', 30 => 'u', 31 => 'xm', 32 => 'sub', 33 => 'nobr', 34 => 'sup', 35 => 'ruby', 36 => 'var', 37 => 'span', 38 => 'wbr', 39 => 'time', );

Description

@var array List of text-level elements for inline formatting.

Methods

1. text

Declaration

public function text(
    string $text
) : string
{
}

Description

Parse the given Markdown text and convert it to HTML.

This method processes the input text by standardizing line breaks, removing surrounding line breaks, and splitting the text into lines, which are then processed to generate the final HTML markup.

Parameters

$text

The Markdown text to parse.

Return

string

The converted HTML markup.

2. setBreaksEnabled

Declaration

public function setBreaksEnabled(
    bool $breaksEnabled
) : $this
{
}

Description

Enable or disable line breaks in the parsed output.

Parameters

$breaksEnabled

Flag indicating whether to enable line breaks.

Return

$this
3. setMarkupEscaped

Declaration

public function setMarkupEscaped(
    bool $markupEscaped
) : $this
{
}

Description

Escape HTML markup in the parsed output.

Parameters

$markupEscaped

Flag indicating whether to escape HTML markup.

Return

$this
4. setUrlsLinked

Declaration

public function setUrlsLinked(
    bool $urlsLinked
) : $this
{
}

Description

Enable or disable automatic linking of URLs in the parsed output.

Parameters

$urlsLinked

Flag indicating whether to link URLs.

Return

$this
5. setSafeMode

Declaration

public function setSafeMode(
    bool $safeMode
) : $this
{
}

Description

Enable or disable safe mode for handling links.

Parameters

$safeMode

Flag indicating whether to enable safe mode.

Return

$this
6. lines

Declaration

protected function lines(
    array $lines
) : string
{
}

Description

Process the lines of Markdown text to identify blocks and convert them to HTML.

This method analyzes the provided lines, identifies different block types, and constructs the corresponding HTML output.

Parameters

$lines

The lines of text to process.

Return

string

The generated HTML markup.

7. isBlockContinuable

Declaration

protected function isBlockContinuable(
    string $type
) : bool
{
}

Description

Check if the specified block type can be continued.

Parameters

$type

The type of the block to check.

Return

bool

True if the block type can be continued, false otherwise.

8. isBlockCompletable

Declaration

protected function isBlockCompletable(
    string $type
) : bool
{
}

Description

Check if a block type is completable.

This method checks if a method exists for completing a block of the specified type.

Parameters

$type

The block type to check.

Return

bool

True if the block type can be completed, false otherwise.

9. blockCode

Declaration

protected function blockCode(
    array $line,
    array|null $block = null
) : array|null
{
}

Description

Parse a code block from a line of text.

This method checks if the line represents the start of a code block and constructs the block if valid.

Parameters

$line

The line of text to process.

$block

The current block (if any).

Return

array|null

The constructed code block or null if not applicable.

10. blockCodeContinue

Declaration

protected function blockCodeContinue(
    array $line,
    array $block
) : array|null
{
}

Description

Continue processing a code block.

This method appends additional lines to an existing code block.

Parameters

$line

The line of text to process.

$block

The current block being processed.

Return

array|null

The updated code block or null if not applicable.

11. blockCodeComplete

Declaration

protected function blockCodeComplete(
    array $block
) : array
{
}

Description

Complete the code block.

This method finalizes the formatting of a completed code block.

Parameters

$block

The block to complete.

Return

array

The completed code block.

12. blockFencedCodeComplete

Declaration

protected function blockFencedCodeComplete(
    array $line,
    array $block
) : array|null
{
}

Description

Continue processing a fenced code block.

This method appends additional lines to an existing fenced code block.

Parameters

$line

The line of text to process.

$block

The current fenced code block being processed.

Return

array|null

The updated fenced code block or null if not applicable.

13. blockComment

Declaration

protected function blockComment(
    array $line
) : array|null
{
}

Description

Parse a comment block from a line of text.

This method checks if the line represents a comment block and constructs it if valid.

Parameters

$line

The line of text to process.

Return

array|null

The constructed comment block or null if not applicable.

14. blockCommentContinue

Declaration

protected function blockCommentContinue(
    array $line,
    array $block
) : array|null
{
}

Description

Continue processing a comment block.

This method appends additional lines to an existing comment block.

Parameters

$line

The line of text to process.

$block

The current comment block being processed.

Return

array|null

The updated comment block or null if not applicable.

15. blockFencedCode

Declaration

protected function blockFencedCode(
    array $line
) : array|null
{
}

Description

Parse a fenced code block from a line of text.

This method checks if the line represents the start of a fenced code block and constructs the block if valid.

Parameters

$line

The line of text to process.

Return

array|null

The constructed fenced code block or null if not applicable.

16. blockFencedCodeContinue

Declaration

protected function blockFencedCodeContinue(
    array $line,
    array $block
) : array|null
{
}

Description

Continue parsing a fenced code block from subsequent lines.

This method handles additional lines that continue the fenced code block. It appends the text to the block until it is completed or interrupted.

Parameters

$line

The current line of text being processed.

$block

The existing fenced code block being built.

Return

array|null

The updated fenced code block or null if it remains incomplete.

17. blockHeader

Declaration

protected function blockHeader(
    array $block
) : array
{
}

Description

Complete the fenced code block.

This method finalizes the formatting of a completed fenced code block.

Parameters

$block

The fenced code block to complete.

Return

array

The completed fenced code block.

18. blockList

Declaration

protected function blockList(
    array $line
) : array|null
{
}

Description

Parse a list from a line of text.

This method checks if the line represents a list item and constructs the list block if valid.

Parameters

$line

The line of text to process.

Return

array|null

The constructed list block or null if not applicable.

19. blockListContinue

Declaration

protected function blockListContinue(
    array $line,
    array $block
) : array|null
{
}

Description

Continue processing a list.

This method appends additional items to an existing list block.

Parameters

$line

The line of text to process.

$block

The current list block being processed.

Return

array|null

The updated list block or null if not applicable.

20. blockListComplete

Declaration

protected function blockListComplete(
    array $block
) : array
{
}

Description

Complete the list block.

This method finalizes the formatting of a completed list block.

Parameters

$block

The list block to complete.

Return

array

The completed list block.

21. blockQuote

Declaration

protected function blockQuote(
    array $line
) : array|null
{
}

Description

Parse a block quote from a line of text.

This method checks if the line starts with a '>' character and captures the quote text.

Parameters

$line

The line of text to process.

Return

array|null

The constructed blockquote or null if not applicable.

22. blockQuoteContinue

Declaration

protected function blockQuoteContinue(
    array $line,
    array $block
) : array|null
{
}

Description

Continue processing a block quote.

This method appends additional lines to an existing block quote if they start with a '>'.

Parameters

$line

The line of text to process.

$block

The current block quote being processed.

Return

array|null

The updated block quote or null if not applicable.

23. blockRule

Declaration

protected function blockRule(
    array $line
) : array|null
{
}

Description

Parse a horizontal rule from a line of text.

This method checks for repeated characters to determine if a horizontal rule is present.

Parameters

$line

The line of text to process.

Return

array|null

The constructed horizontal rule or null if not applicable.

24. blockSetextHeader

Declaration

protected function blockSetextHeader(
    array $line,
    array|null $block = null
) : array|null
{
}

Description

Parse a Setext header from a line of text.

This method constructs a header based on the presence of underlining characters.

Parameters

$line

The line of text to process.

$block

The current block being processed.

Return

array|null

The updated block or null if not applicable.

25. blockMarkup

Declaration

protected function blockMarkup(
    array $line
) : array|null
{
}

Description

Parse custom markup from a line of text.

This method constructs a block based on the presence of HTML-like tags.

Parameters

$line

The line of text to process.

Return

array|null

The constructed markup block or null if not applicable.

26. blockMarkupContinue

Declaration

protected function blockMarkupContinue(
    array $line
) : array|null
{
}

Description

Parse a reference link definition from a line of text.

This method constructs a reference link that can be used later in the document.

Parameters

$line

The line of text to process.

Return

array|null

The constructed reference or null if not applicable.

27. blockReference

Declaration

protected function blockReference(
    array $line
) : array|null
{
}

Description

Parse a reference link definition from a line of text.

This method constructs a reference link that can be used later in the document.

Parameters

$line

The line of text to process.

Return

array|null

The constructed reference or null if not applicable.

28. blockTable

Declaration

protected function blockTable(
    array $line,
    array|null $block = null
) : array|null
{
}

Description

Parse a table header from a line of text.

This method checks if the line represents a table structure and constructs it if valid.

Parameters

$line

The line of text to process.

$block

The current block being processed.

Return

array|null

The constructed table block or null if not applicable.

29. blockTableContinue

Declaration

protected function blockTableContinue(
    array $line,
    array $block
) : array|null
{
}

Description

Continue processing a table.

This method appends additional rows to an existing table block.

Parameters

$line

The line of text to process.

$block

The current table block being processed.

Return

array|null

The updated table block or null if not applicable.

30. paragraph

Declaration

protected function paragraph(
    array $line
) : array
{
}

Description

Parse a paragraph from a line of text.

This method constructs a paragraph block from the provided text.

Parameters

$line

The line of text to process.

Return

array

The constructed paragraph block.

31. line

Declaration

public function line(
    string $text,
    array $nonNestables = array ( )
) : string
{
}

Description

Process a line of text and convert inline elements.

This method identifies markers in the text and processes them into HTML-like structures.

Parameters

$text

The line of text to process.

$nonNestables

An array of non-nestable inline types.

Return

string

The processed markup with inline elements.

32. inlineCode

Declaration

protected function inlineCode(
    array $excerpt
) : array|null
{
}

Description

Parse inline code from the excerpt.

This method checks for code markers and captures the code content.

Parameters

$excerpt

The excerpt to process.

Return

array|null

The inline code element or null if not applicable.

33. inlineEmailTag

Declaration

protected function inlineEmailTag(
    array $excerpt
) : array|null
{
}

Description

Parse an email tag from the excerpt.

This method identifies email addresses formatted within angle brackets.

Parameters

$excerpt

The excerpt to process.

Return

array|null

The email link element or null if not applicable.

34. inlineEmphasis

Declaration

protected function inlineEmphasis(
    array $excerpt
) : array|null
{
}

Description

Parse emphasis (bold/italic) from the excerpt.

This method checks for markers indicating strong or emphasized text.

Parameters

$excerpt

The excerpt to process.

Return

array|null

The emphasis element or null if not applicable.

35. inlineEscapeSequence

Declaration

protected function inlineEscapeSequence(
    array $excerpt
) : array|null
{
}

Description

Handle escape sequences for special characters.

This method checks for special characters that are preceded by a backslash.

Parameters

$excerpt

The excerpt to process.

Return

array|null

The escaped character element or null if not applicable.

36. inlineImage

Declaration

protected function inlineImage(
    array $excerpt
) : array|null
{
}

Description

Parse an inline image from the excerpt.

This method identifies image links formatted with brackets and captures the source and alt text.

Parameters

$excerpt

The excerpt to process.

Return

array|null

The image element or null if not applicable.

37. inlineLink

Declaration

protected function inlineLink(
    array $excerpt
) : array|null
{
}

Description

Processes inline links in the provided text.

Parameters

$excerpt

Contains the text to be processed.

Return

array|null

Returns an array containing the extent of the match and the link element, or null if no match is found.

38. inlineMarkup

Declaration

protected function inlineMarkup(
    array $excerpt
) : array|null
{
}

Description

Processes inline HTML markup in the provided text.

Parameters

$excerpt

Contains the text to be processed.

Return

array|null

Returns an array with the markup and its extent, or null if no valid markup is found.

39. inlineSpecialCharacter

Declaration

protected function inlineSpecialCharacter(
    array $excerpt
) : array|null
{
}

Description

Processes inline special characters in the provided text.

Parameters

$excerpt

Contains the text to be processed.

Return

array|null

Returns an array with the escaped character and its extent, or null if no special character is found.

40. inlineStrikethrough

Declaration

protected function inlineStrikethrough(
    array $excerpt
) : array|null
{
}

Description

Processes inline strikethrough text in the provided text.

Parameters

$excerpt

Contains the text to be processed.

Return

array|null

Returns an array with the extent of the strikethrough and the corresponding element, or null if no match is found.

41. inlineUrl

Declaration

protected function inlineUrl(
    array $excerpt
) : array|null
{
}

Description

Processes inline URLs in the provided text.

Parameters

$excerpt

Contains the text to be processed.

Return

array|null

Returns an array with the extent and URL element, or null if no valid URL is found.

42. inlineUrlTag

Declaration

protected function inlineUrlTag(
    array $excerpt
) : array|null
{
}

Description

Processes inline URL tags formatted in angle brackets.

Parameters

$excerpt

Contains the text to be processed.

Return

array|null

Returns an array with the extent and URL element, or null if no valid tag is found.

43. unmarkedText

Declaration

protected function unmarkedText(
    string $text
) : string
{
}

Description

Processes unmarked text by converting line breaks to HTML.

Parameters

$text

The text to be processed.

Return

string

The processed text with line breaks converted to HTML.

44. element

Declaration

protected function element(
    array $element
) : string
{
}

Description

Generates HTML markup for a given element.

Parameters

$element

The element to be rendered as HTML.

Return

string

The generated HTML markup for the element.

45. elements

Declaration

protected function elements(
    array $elements
) : string
{
}

Description

Generates HTML markup for multiple elements.

Parameters

$elements

An array of elements to be rendered as HTML.

Return

string

The generated HTML markup for all elements.

46. li

Declaration

protected function li(
    array $lines
) : string
{
}

Description

Processes list items by converting lines to HTML list markup.

Parameters

$lines

An array of lines representing list items.

Return

string

The generated HTML for the list items.

47. parse

Declaration

public function parse(
    string $text
) : string
{
}

Description

Parses the input text and returns the generated HTML markup.

Parameters

$text

The text to be parsed.

Return

string

The generated HTML markup.

48. sanitiseElement

Declaration

protected function sanitiseElement(
    array $element
) : array
{
}

Description

Sanitizes an HTML element to prevent XSS vulnerabilities.

Parameters

$element

The element to be sanitized.

Return

array

The sanitized element.

49. filterUnsafeUrlInAttribute

Declaration

protected function filterUnsafeUrlInAttribute(
    array $element,
    string $attribute
) : array
{
}

Description

Filters unsafe URLs in a given attribute of an HTML element.

Parameters

$element

The element containing the attribute to be filtered.

$attribute

The name of the attribute to be checked.

Return

array

The element with the filtered attribute.

50. escape

Declaration

protected static function escape(
    string $text,
    bool $allowQuotes = false
) : string
{
}

Description

Escapes special characters for HTML output.

Parameters

$text

The text to be escaped.

$allowQuotes

Whether to allow unescaped quotes.

Return

string

The escaped text.

51. striAtStart

Declaration

protected static function striAtStart(
    string $string,
    string $needle
) : bool
{
}

Description

Checks if a string starts with a given needle.

Parameters

$string

The string to be checked.

$needle

The substring to check for.

Return

bool

True if the string starts with the needle, false otherwise.

52. instance

Declaration

public static function instance(
    string $name = 'default'
) : static
{
}

Description

Retrieves an instance of the class.

Parameters

$name

The name of the instance.

Return

static

The instance of the class.

MagicObject\Util\PicoArrayUtil

Declaration

class PicoArrayUtil { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoArrayUtil

Utility class for performing various array operations, particularly key transformations between camelCase and snake_case formats.

This class provides static methods and cannot be instantiated.

Methods

2. camelize

Declaration

public static function camelize(
    array|object|stdClass $input
) : array
{
}

Description

Converts the keys of an array or object to camelCase.

This method can process both associative arrays and objects.

Example:

 <?php
 $data = ['first_name' => 'John', 'last_name' => 'Doe'];
 $camelized = PicoArrayUtil::camelize($data);
 // $camelized is ['firstName' => 'John', 'lastName' => 'Doe']

Parameters

$input

Array or object containing data to be processed.

Return

array

Processed array with camelCase keys.

3. snakeize

Declaration

public static function snakeize(
    array|object|stdClass $input
) : array
{
}

Description

Converts the keys of an array or object to snake_case.

This method can process both associative arrays and objects.

Example:

 <?php
 $data = ['firstName' => 'John', 'lastName' => 'Doe'];
 $snakeized = PicoArrayUtil::snakeize($data);
 // $snakeized is ['first_name' => 'John', 'last_name' => 'Doe']

Parameters

$input

Array or object containing data to be processed.

Return

array

Processed array with snake_case keys.

4. _camelize

Declaration

private static function _camelize(
    array
) : void
{
}

Description

Recursively converts array keys to camelCase.

This method operates by reference to avoid unnecessary copies.

Parameters

&$array

Array containing data to be processed by reference.

Return

void
5. _snakeize

Declaration

private static function _snakeize(
    array
) : void
{
}

Description

Recursively converts array keys to snake_case.

This method operates by reference to avoid unnecessary copies.

Parameters

&$array

Array containing data to be processed by reference.

Return

void
6. normalizeArrayIndicesRecursive

Declaration

public static function normalizeArrayIndicesRecursive(
    array $array
) : array
{
}

Description

Recursively normalizes array indices by converting string integer keys into numeric sequential indices, while retaining non-integer keys.

This method processes multi-dimensional arrays of unlimited depth. If a key is a string that represents an integer (e.g., "0", "1"), it is converted into a numeric sequential index. Non-integer or non-string keys remain unchanged.

Parameters

$array

The input array to normalize.

Return

array

The normalized array with modified indices.

MagicObject\Util\PicoCurlUtil

Declaration

class PicoCurlUtil { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoCurlUtil

This class provides an interface for making HTTP requests using cURL.

Properties

1. curl

Declaration

private CurlHandle $curl;

Description

cURL handle

2. responseHeaders

Declaration

private string[] $responseHeaders = array();

Description

Response headers from the last request

3. responseBody

Declaration

private string $responseBody = '';

Description

Response body from the last request

4. httpCode

Declaration

private int $httpCode = 0;

Description

HTTP status code from the last request

Methods

1. __construct

Declaration

public function __construct()
{
}

Description

PicoCurlUtil constructor. Initializes the cURL handle.

2. setOption

Declaration

public function setOption(
    int $option,
    mixed $value
)
{
}

Description

Sets a cURL option.

Parameters

$option

cURL option to set

$value

Value for the cURL option

3. setSslVerification

Declaration

public function setSslVerification(
    bool $verify
)
{
}

Description

Enables or disables SSL verification.

Parameters

$verify

If true, SSL verification is enabled; if false, it is disabled.

4. get

Declaration

public function get(
    string $url,
    array $headers = array ( )
) : string
{
}

Description

Executes a GET request.

Parameters

$url

URL for the request

$headers

Additional headers for the request

Return

string

Response body

Throws

CurlException

If an error occurs during cURL execution

5. post

Declaration

public function post(
    string $url,
    mixed $data,
    array $headers = array ( )
) : string
{
}

Description

Executes a POST request.

Parameters

$url

URL for the request

$data

Data to send

$headers

Additional headers for the request

Return

string

Response body

Throws

CurlException

If an error occurs during cURL execution

6. put

Declaration

public function put(
    string $url,
    mixed $data,
    array $headers = array ( )
) : string
{
}

Description

Executes a PUT request.

Parameters

$url

URL for the request

$data

Data to send

$headers

Additional headers for the request

Return

string

Response body

Throws

CurlException

If an error occurs during cURL execution

7. delete

Declaration

public function delete(
    string $url,
    array $headers = array ( )
) : string
{
}

Description

Executes a DELETE request.

Parameters

$url

URL for the request

$headers

Additional headers for the request

Return

string

Response body

Throws

CurlException

If an error occurs during cURL execution

8. execute

Declaration

private function execute() : string
{
}

Description

Executes the cURL request and processes the response.

Return

string

Response body

Throws

CurlException

If an error occurs during cURL execution

9. getHttpCode

Declaration

public function getHttpCode() : int
{
}

Description

Gets the HTTP status code from the last response.

Return

int

HTTP status code

10. getResponseHeaders

Declaration

public function getResponseHeaders() : array
{
}

Description

Gets the response headers from the last request.

Return

array

Array of response headers

11. close

Declaration

public function close()
{
}

Description

Closes the cURL handle.

12. __destruct

Declaration

public function __destruct()
{
}

Description

Destructor to close cURL when the object is destroyed.

MagicObject\Util\PicoDateTimeUtil

Declaration

class PicoDateTimeUtil { }

Package

MagicObject

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoDateTimeUtil

A utility class for parsing date and time strings into DateTime objects. This class provides methods to convert various date formats into a standardized DateTime object for easier manipulation and formatting.

It supports multiple date formats, including ISO 8601 and RFC 2822, as well as local and custom formats and Unix timestamps.

Methods

1. parseDateTime

Declaration

public static function parseDateTime(
    string|int $dateString
) : DateTime|null
{
}

Description

Parse DateTime from a string or Unix timestamp.

This method attempts to parse a given date string or Unix timestamp into a DateTime object using multiple predefined formats. If the parsing is successful, it returns the corresponding DateTime object; otherwise, it returns null.

Parameters

$dateString

The date string or Unix timestamp to be parsed.

Return

DateTime|null

Returns a DateTime object if parsing is successful,

MagicObject\Util\PicoEnvironmentVariable

Declaration

class PicoEnvironmentVariable { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoEnvironmentVariable

A utility class for handling environment variable replacements within strings and data structures.

Methods

1. replaceValueAll

Declaration

public static function replaceValueAll(
    array|object $values,
    array $collection,
    bool $recursive = false
) : array|object
{
}

Description

Replace all values in a collection with other properties.

Parameters

$values

Values to process.

$collection

Collection of replacement values.

$recursive

Flag indicating if the process should be recursive.

Return

array|object

Processed values with replacements applied.

2. replaceValueAllArray

Declaration

public static function replaceValueAllArray(
    array $values,
    array $collection,
    bool $recursive = false
) : array
{
}

Description

Replace all values in an array with other properties.

Parameters

$values

Values to process.

$collection

Collection of replacement values.

$recursive

Flag indicating if the process should be recursive.

Return

array

Processed array with replacements applied.

3. replaceValueAllObject

Declaration

public static function replaceValueAllObject(
    stdClass|object $values,
    array $collection,
    bool $recursive = false
) : stdClass|object
{
}

Description

Replace all values in an object with other properties.

Parameters

$values

Values to process.

$collection

Collection of replacement values.

$recursive

Flag indicating if the process should be recursive.

Return

stdClass|object

Processed object with replacements applied.

4. replaceWithOtherProperties

Declaration

public static function replaceWithOtherProperties(
    string $value,
    array $collection
) : mixed
{
}

Description

Replace strings with environment variable names from a string.

Parameters

$value

Value to process.

$collection

Collection of replacement values.

Return

mixed

Processed value with replacements applied.

5. getOtherValue

Declaration

public static function getOtherValue(
    string $key,
    array $collection
) : mixed|null
{
}

Description

Retrieve a value from the collection by its key.

Parameters

$key

Key name to retrieve.

$collection

Collection to search in.

Return

mixed|null

Retrieved value or null if not found.

6. replaceSysEnvAll

Declaration

public static function replaceSysEnvAll(
    array $values,
    bool $recursive = false
) : array
{
}

Description

Replace all values in an array with environment variable names.

Parameters

$values

Values to process.

$recursive

Flag indicating if the process should be recursive.

Return

array

Processed values with replacements applied.

7. replaceWithEnvironmentVariable

Declaration

public static function replaceWithEnvironmentVariable(
    string $value
) : string
{
}

Description

Replace strings with environment variable names from a string.

Parameters

$value

Value to process.

Return

string

Processed value with replacements applied.

8. replaceSysEnv

Declaration

public static function replaceSysEnv(
    string $value
) : string
{
}

Description

Replace a value with its corresponding environment variable.

Parameters

$value

Value to process.

Return

string

Processed value with replacements applied.

9. getVariables

Declaration

public static function getVariables(
    string $value
) : array
{
}

Description

Extract environment variable names from a string.

Parameters

$value

Value to process.

Return

array

List of variable names extracted.

MagicObject\Util\PicoGenericObject

Declaration

class PicoGenericObject extends stdClass { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoGenericObject

A generic object that allows dynamic property management. This class extends stdClass and provides methods to load, set, get, unset, and check properties dynamically.

Properties can be accessed using camelCase naming conventions.

Methods

1. __construct

Declaration

public function __construct(
    MagicObject|self|stdClass|array|null $data = null
)
{
}

Description

Constructor

Initializes the object with optional initial data.

Parameters

$data

Initial data to load into the object.

2. loadData

Declaration

public function loadData(
    stdClass|array $data
) : self
{
}

Description

Load data into the object.

Accepts either an associative array or an object, converting its keys to camelCase format before loading.

Example:

 <?php
 $obj = new PicoGenericObject();
 $obj->loadData(['first_name' => 'John', 'last_name' => 'Doe']);
 echo $obj->get('firstName'); // Outputs: John

Parameters

$data

Data to be loaded.

Return

self

Returns the current instance for method chaining.

3. set

Declaration

public function set(
    string $propertyName,
    mixed $propertyValue
) : self
{
}

Description

Set a property value.

Converts the property name to camelCase and assigns the value.

Example:

 <?php
 $obj = new PicoGenericObject();
 $obj->set('first_name', 'John');
 echo $obj->get('firstName'); // Outputs: John

Parameters

$propertyName

Name of the property.

$propertyValue

Value to set.

Return

self

Returns the current instance for method chaining.

4. get

Declaration

public function get(
    string $propertyName
) : mixed|null
{
}

Description

Get a property value.

Retrieves the value of a property, returning null if not set.

Example:

 <?php
 $value = $obj->get('firstName'); // Retrieves the value of 'firstName'

Parameters

$propertyName

Name of the property.

Return

mixed|null

The value of the property or null if not set.

5. __set

Declaration

public function __set(
    string $name,
    mixed $value
) : void
{
}

Description

Magic method to set property values dynamically.

This method allows setting properties without directly calling set().

Example:

 <?php
 $obj->firstName = 'John'; // Calls __set() internally

Parameters

$name

Name of the property.

$value

Value to set.

Return

void
6. __get

Declaration

public function __get(
    string $name
) : mixed|null
{
}

Description

Magic method to get property values dynamically.

This method allows getting properties without directly calling get().

Example:

 <?php
 $value = $obj->firstName; // Calls __get() internally

Parameters

$name

Name of the property to get.

Return

mixed|null

The value stored in the property or null if not set.

7. __isset

Declaration

public function __isset(
    string $name
) : bool
{
}

Description

Check if a property is set.

Example:

 <?php
 if ($obj->issetFirstName()) {
     // Do something
 }

Parameters

$name

Name of the property.

Return

bool

True if the property is set, false otherwise.

8. __unset

Declaration

public function __unset(
    string $name
) : self
{
}

Description

Unset a property value.

Example:

 <?php
 $obj->unsetFirstName(); // Removes the property 'firstName'

Parameters

$name

Name of the property.

Return

self

Returns the current instance for method chaining.

9. __call

Declaration

public function __call(
    string $method,
    array $params
) : mixed|null
{
}

Description

Magic method called when invoking undefined methods.

This method handles dynamic method calls for property management.

Supported methods:

  • isset<PropertyName>: Checks if the property is set.

    • Example: $obj->issetFoo() returns true if property foo is set.
  • is<PropertyName>: Checks if the property is set and equals 1 (truthy).

    • Example: $obj->isFoo() returns true if property foo is set and is equal to 1.
  • get<PropertyName>: Retrieves the value of the property.

    • Example: $value = $obj->getFoo() gets the value of property foo.
  • set<PropertyName>: Sets the value of the property.

    • Example: $obj->setFoo($value) sets the property foo to $value.
  • unset<PropertyName>: Unsets the property.

    • Example: $obj->unsetFoo() removes the property foo.

Parameters

$method

Method name.

$params

Parameters for the method.

Return

mixed|null

The result of the method call or null if not applicable.

MagicObject\Util\PicoHttpCache

Declaration

class PicoHttpCache { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoHttpCache

A utility class for managing HTTP caching headers.

This class provides methods to set cache lifetime for HTTP responses.

Methods

2. cacheLifetime

Declaration

public static function cacheLifetime(
    int $lifetime
) : void
{
}

Description

Send headers to the browser to cache the current URL.

This method sets the appropriate headers for caching, including the expiration date and cache control directives.

Parameters

$lifetime

Cache lifetime in seconds.

Return

void

Throws

InvalidArgumentException

if $lifetime is negative.

MagicObject\Util\PicoIniUtil

Declaration

class PicoIniUtil { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Utility class for handling INI file operations.

This class provides methods for reading from and writing to INI files, as well as parsing INI strings into arrays and vice versa.

Methods

2. writeIniFile

Declaration

public static function writeIniFile(
    array $array,
    string $path
) : bool
{
}

Description

Write an array to an INI file.

This method converts an array into an INI format and saves it to the specified file path.

Parameters

$array

The array to write to the INI file.

$path

The file path where the INI file will be saved.

Return

bool

True on success, false on failure.

3. getContent

Declaration

private static function getContent(
    string $content,
    array $array
) : string
{
}

Description

Generate INI content from a simple array.

Parameters

$content

The existing content (usually empty).

$array

The array to convert to INI format.

Return

string

The formatted INI content.

4. getContentMulti

Declaration

private static function getContentMulti(
    string $content,
    array $array
) : string
{
}

Description

Generate INI content from a multidimensional array.

Parameters

$content

The existing content (usually empty).

$array

The multidimensional array to convert to INI format.

Return

string

The formatted INI content.

5. parseIniFile

Declaration

public static function parseIniFile(
    string $path
) : array|false
{
}

Description

Parse an INI file from the specified path.

Parameters

$path

The file path of the INI file to parse.

Return

array|false

The parsed INI data as an array, or false on failure.

6. parseIniString

Declaration

public static function parseIniString(
    string $str
) : array|false
{
}

Description

Parse an INI string into an array.

Parameters

$str

The INI string to parse.

Return

array|false

The parsed INI data as an array, or false on failure.

7. matchValue

Declaration

public static function matchValue(
    string $line
) : bool
{
}

Description

Check if the line is invalid (empty or a comment).

Parameters

$line

The line to check.

Return

bool

True if the line is invalid, false otherwise.

8. invalidLine

Declaration

public static function invalidLine(
    string $line
) : bool
{
}

Description

Check if a line is invalid.

A line is considered invalid if it is empty or starts with a comment character (# or ;).

Parameters

$line

The line to check.

Return

bool

True if the line is invalid, false otherwise.

9. removeSurroundingQuotes

Declaration

public static function removeSurroundingQuotes(
    string $value
) : string
{
}

Description

Remove surrounding quotes from a value.

This method checks if the given value is surrounded by either double or single quotes and removes those quotes if they are present.

Parameters

$value

The value to fix.

Return

string

The cleaned value without surrounding quotes.

10. removeSurroundingQuotesRegex

Declaration

public static function removeSurroundingQuotesRegex(
    string $value
) : string
{
}

Description

Remove surrounding quotes from a value using regex.

This method checks if the given value matches the pattern of being surrounded by double or single quotes and removes them if so.

Parameters

$value

The value to fix.

Return

string

The cleaned value without surrounding quotes.

11. organizeValue

Declaration

public static function organizeValue(
    array $ret,
    string $insideSection,
    string $arrName,
    array $matches,
    mixed $value
) : array
{
}

Description

Fix and organize the value in the parsed result.

This method ensures that the provided array is correctly formatted based on the given parameters, handling nested structures as needed.

Parameters

$ret

The parsed result array to update.

$insideSection

The name of the current section.

$arrName

The name of the array key to update.

$matches

Matches found during parsing.

$value

The value to assign to the array.

Return

array

The updated parsed result array.

MagicObject\Util\PicoLocale

Declaration

class PicoLocale { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Locale

The PicoLocale class serves as a container for a collection of predefined locale constants. These constants represent different locale identifiers for various countries, regions, and languages, using the format of language-region (e.g., "en_US" for English in the United States, "fr_FR" for French in France).

Each constant corresponds to a specific locale, which can be used in applications to handle internationalization (i18n), localization (l10n), and formatting of data such as dates, currencies, and numbers, based on the user's regional settings.

Constants

const EN_IE = "en_IE";
const RO_MD = "ro_MD";
const BR = "br";
const EN_GY = "en_GY";
const ES_GT = "es_GT";
const SHI_TFNG_M = "shi-Tfng_M";
const MR = "mr";
const BS = "bs";
const EN_AS = "en_AS";
const KSF = "ksf";
const BS_CYRL = "bs-Cyrl";
const EN_PR = "en_PR";
const MS = "ms";
const SR_LATN_ME = "sr-Latn_ME";
const MT = "mt";
const HA = "ha";
const NB_NO = "nb_NO";
const EN_SE = "en_SE";
const EN_BZ = "en_BZ";
const PT_BR = "pt_BR";
const OR_IN = "or_IN";
const IS_IS = "is_IS";
const MN_MN = "mn_MN";
const AR_IQ = "ar_IQ";
const HE = "he";
const IT_SM = "it_SM";
const EN_AT = "en_AT";
const BAS = "bas";
const CKB = "ckb";
const MY = "my";
const ZH_CN = "zh_CN";
const MER = "mer";
const KS_ARAB_IN = "ks-Arab_IN";
const EN_JM = "en_JM";
const DZ_BT = "dz_BT";
const MS_ARAB_BN = "ms-Arab_BN";
const CY_GB = "cy_GB";
const SG = "sg";
const IT_CH = "it_CH";
const TEO_KE = "teo_KE";
const DE_LU = "de_LU";
const EN_US = "en_US";
const HI = "hi";
const HU_HU = "hu_HU";
const UZ_LATN_UZ = "uz-Latn_UZ";
const AF_NA = "af_NA";
const SI = "si";
const FR_BI = "fr_BI";
const GA_IE = "ga_IE";
const MFE = "mfe";
const EN_CA = "en_CA";
const NE_IN = "ne_IN";
const RWK_TZ = "rwk_TZ";
const EN_AU = "en_AU";
const SK = "sk";
const TEO = "teo";
const EN_PT = "en_PT";
const EN_NG = "en_NG";
const SL = "sl";
const TK_TM = "tk_TM";
const TZM = "tzm";
const EE_GH = "ee_GH";
const KDE = "kde";
const SN = "sn";
const DYO_SN = "dyo_SN";
const EN_SG = "en_SG";
const MAS_TZ = "mas_TZ";
const SO = "so";
const NYN_UG = "nyn_UG";
const BR_FR = "br_FR";
const FR_BJ = "fr_BJ";
const ES_IC = "es_IC";
const PT_MZ = "pt_MZ";
const HR = "hr";
const AZ = "az";
const SQ = "sq";
const SR = "sr";
const SW_KE = "sw_KE";
const CA = "ca";
const HU = "hu";
const ET_EE = "et_EE";
const LAG_TZ = "lag_TZ";
const BN_IN = "bn_IN";
const NB = "nb";
const SV = "sv";
const TH_TH = "th_TH";
const ML_IN = "ml_IN";
const SR_RS = "sr_RS";
const SW = "sw";
const ND = "nd";
const TA_IN = "ta_IN";
const FR_MQ = "fr_MQ";
const HY = "hy";
const EN_TO = "en_TO";
const ES_AR = "es_AR";
const NE = "ne";
const PT_AO = "pt_AO";
const NE_NP = "ne_NP";
const AR_BH = "ar_BH";
const EN_SI = "en_SI";
const BO_IN = "bo_IN";
const HI_IN = "hi_IN";
const SEH = "seh";
const DE_DE = "de_DE";
const KO_KP = "ko_KP";
const FR_BL = "fr_BL";
const FR_MR = "fr_MR";
const CA_AD = "ca_AD";
const FA_IR = "fa_IR";
const NL = "nl";
const ES_PR = "es_PR";
const EN_PW = "en_PW";
const RN_BI = "rn_BI";
const NN = "nn";
const KK = "kk";
const EN_DK = "en_DK";
const SL_SI = "sl_SI";
const DUA = "dua";
const KEA = "kea";
const MS_ARAB_MY = "ms-Arab_MY";
const IG_NG = "ig_NG";
const KLN = "kln";
const YO = "yo";
const FR_DZ = "fr_DZ";
const SV_FI = "sv_FI";
const FR_SY = "fr_SY";
const RU_MD = "ru_MD";
const EN_ZW = "en_ZW";
const BRX_IN = "brx_IN";
const SW_UG = "sw_UG";
const FIL_PH = "fil_PH";
const CS = "cs";
const PT_GW = "pt_GW";
const BN_BD = "bn_BD";
const DE_AT = "de_AT";
const FR_PF = "fr_PF";
const LUO = "luo";
const SK_SK = "sk_SK";
const AR_001 = "ar_001";
const ES_US = "es_US";
const EN_SK = "en_SK";
const TA = "ta";
const FR_HT = "fr_HT";
const MK_MK = "mk_MK";
const OM_KE = "om_KE";
const DA_DK = "da_DK";
const EN_ME = "en_ME";
const KO_KR = "ko_KR";
const FF_SN = "ff_SN";
const ID = "id";
const EN_KY = "en_KY";
const KDE_TZ = "kde_TZ";
const SHI = "shi";
const CY = "cy";
const EN_ES = "en_ES";
const MGH = "mgh";
const EN_TR = "en_TR";
const SR_ME = "sr_ME";
const TE = "te";
const FR_GN = "fr_GN";
const FO_FO = "fo_FO";
const EN_NL = "en_NL";
const IG = "ig";
const IT_IT = "it_IT";
const UK_UA = "uk_UA";
const TG = "tg";
const EN_DM = "en_DM";
const BM_ML = "bm_ML";
const VAI = "vai";
const EN_SL = "en_SL";
const II = "ii";
const EN_150 = "en_150";
const SES = "ses";
const TH = "th";
const TI = "ti";
const EN_IM = "en_IM";
const RU_KZ = "ru_KZ";
const FR_MU = "fr_MU";
const IU_CANS_CA = "iu-Cans_CA";
const CS_CZ = "cs_CZ";
const AR_AE = "ar_AE";
const TE_IN = "te_IN";
const TK = "tk";
const BRX = "brx";
const HAW = "haw";
const TZM_MA = "tzm_MA";
const SO_DJ = "so_DJ";
const UZ_UZ = "uz_UZ";
const EN_BA = "en_BA";
const TO = "to";
const EN_MG = "en_MG";
const EWO_CM = "ewo_CM";
const AR_MR = "ar_MR";
const NL_AW = "nl_AW";
const EN_IN = "en_IN";
const MGO = "mgo";
const SN_ZW = "sn_ZW";
const EN_CH = "en_CH";
const EN_TT = "en_TT";
const TR = "tr";
const IS = "is";
const FR_GP = "fr_GP";
const LUY = "luy";
const ES_NI = "es_NI";
const PT_TL = "pt_TL";
const IT = "it";
const MS_ARAB = "ms-Arab";
const DA = "da";
const KLN_KE = "kln_KE";
const IU = "iu";
const EN_BB = "en_BB";
const AR_DZ = "ar_DZ";
const AR_SY = "ar_SY";
const EN_MH = "en_MH";
const MR_IN = "mr_IN";
const EN_GB = "en_GB";
const DE = "de";
const FR_GQ = "fr_GQ";
const EN_NO = "en_NO";
const KY_KG = "ky_KG";
const PT_PT = "pt_PT";
const FR_RW = "fr_RW";
const NUS_SD = "nus_SD";
const ASA = "asa";
const ZH = "zh";
const HA_GH = "ha_GH";
const BO_CN = "bo_CN";
const KAM_KE = "kam_KE";
const DUA_CM = "dua_CM";
const KHQ_ML = "khq_ML";
const UR_IN = "ur_IN";
const EN_LC = "en_LC";
const FR_TD = "fr_TD";
const KSB_TZ = "ksb_TZ";
const GU_IN = "gu_IN";
const OM = "om";
const JMC = "jmc";
const RO_RO = "ro_RO";
const JA_JP = "ja_JP";
const LN_AO = "ln_AO";
const SO_ET = "so_ET";
const EN_GD = "en_GD";
const NL_NL = "nl_NL";
const ES_ES = "es_ES";
const EN_VC = "en_VC";
const OR = "or";
const YO_NG = "yo_NG";
const ES_PY = "es_PY";
const MUA_CM = "mua_CM";
const FA_AF = "fa_AF";
const EN_HK = "en_HK";
const JA = "ja";
const LUO_KE = "luo_KE";
const TWQ = "twq";
const EN_BE = "en_BE";
const ES_UY = "es_UY";
const DJE_NE = "dje_NE";
const LUY_KE = "luy_KE";
const NAQ = "naq";
const SI_LK = "si_LK";
const ZU = "zu";
const ZH_HANS_MO = "zh-Hans_MO";
const FR_KM = "fr_KM";
const ZH_HK = "zh_HK";
const DZ = "dz";
const SWC = "swc";
const ASA_TZ = "asa_TZ";
const JGO_CM = "jgo_CM";
const AZ_CYRL = "az-Cyrl";
const EWO = "ewo";
const GV_GB = "gv_GB";
const TI_ER = "ti_ER";
const BE_BY = "be_BY";
const EN_IS = "en_IS";
const EN_CM = "en_CM";
const UK = "uk";
const CGG_UG = "cgg_UG";
const NYN = "nyn";
const TR_CY = "tr_CY";
const DE_CH = "de_CH";
const FR_TG = "fr_TG";
const JMC_TZ = "jmc_TZ";
const TA_LK = "ta_LK";
const SO_SO = "so_SO";
const ES_DO = "es_DO";
const FR_LU = "fr_LU";
const SHI_MA = "shi_MA";
const EN_SS = "en_SS";
const SWC_CD = "swc_CD";
const KN_IN = "kn_IN";
const HY_AM = "hy_AM";
const EN_IT = "en_IT";
const EN_GG = "en_GG";
const FIL = "fil";
const BAS_CM = "bas_CM";
const EN_TZ = "en_TZ";
const AR_TD = "ar_TD";
const UR = "ur";
const BEZ_TZ = "bez_TZ";
const HAW_US = "haw_US";
const FR_VU = "fr_VU";
const PA = "pa";
const BS_BA = "bs_BA";
const EE_TG = "ee_TG";
const TI_ET = "ti_ET";
const SR_LATN_BA = "sr-Latn_BA";
const EN_GH = "en_GH";
const EE = "ee";
const EN_VG = "en_VG";
const SV_SE = "sv_SE";
const KI_KE = "ki_KE";
const ZH_HANS = "zh-Hans";
const BEM = "bem";
const UZ = "uz";
const AR_YE = "ar_YE";
const FR_NC = "fr_NC";
const SEH_MZ = "seh_MZ";
const RU_UA = "ru_UA";
const FR_SC = "fr_SC";
const AR_KM = "ar_KM";
const EN_ZA = "en_ZA";
const EN_GI = "en_GI";
const MAS_KE = "mas_KE";
const NN_NO = "nn_NO";
const AR_EG = "ar_EG";
const EL = "el";
const EN_RO = "en_RO";
const PL = "pl";
const NL_BE = "nl_BE";
const EN = "en";
const UZ_LATN = "uz-Latn";
const EO = "eo";
const KOK = "kok";
const MAS = "mas";
const FR_FR = "fr_FR";
const ROF = "rof";
const EN_MP = "en_MP";
const DE_BE = "de_BE";
const HR_BA = "hr_BA";
const AR_EH = "ar_EH";
const ES_CL = "es_CL";
const EN_AD = "en_AD";
const ES = "es";
const EN_VI = "en_VI";
const PS = "ps";
const ET = "et";
const NL_SR = "nl_SR";
const VAI_LATN = "vai-Latn";
const PT = "pt";
const EU = "eu";
const KA = "ka";
const FR_NE = "fr_NE";
const EU_ES = "eu_ES";
const MGH_MZ = "mgh_MZ";
const ZU_ZA = "zu_ZA";
const AR_SA = "ar_SA";
const CHR_US = "chr_US";
const CGG = "cgg";
const SQ_MK = "sq_MK";
const LAG = "lag";
const AZ_AZ = "az_AZ";
const ES_VE = "es_VE";
const KS_ARAB = "ks-Arab";
const EN_HR = "en_HR";
const EL_GR = "el_GR";
const EL_CY = "el_CY";
const MFE_MU = "mfe_MU";
const KI = "ki";
const VI = "vi";
const EN_KE = "en_KE";
const RWK = "rwk";
const BEZ = "bez";
const KL = "kl";
const ZH_HANT = "zh-Hant";
const FR_CA = "fr_CA";
const KM = "km";
const ES_HN = "es_HN";
const AGQ_CM = "agq_CM";
const KN = "kn";
const II_CN = "ii_CN";
const MN = "mn";
const EN_BM = "en_BM";
const KO = "ko";
const SV_AX = "sv_AX";
const LN_CD = "ln_CD";
const EN_GM = "en_GM";
const IU_CANS = "iu-Cans";
const FR_MA = "fr_MA";
const ES_CO = "es_CO";
const EN_AG = "en_AG";
const GUZ_KE = "guz_KE";
const KS = "ks";
const ES_PA = "es_PA";
const TWQ_NE = "twq_NE";
const EN_NZ = "en_NZ";
const FR_TN = "fr_TN";
const FA = "fa";
const EN_US_POSI = "en_US_POSI";
const DAV_KE = "dav_KE";
const EN_WS = "en_WS";
const LT_LT = "lt_LT";
const EN_SZ = "en_SZ";
const AR_SD = "ar_SD";
const ROF_TZ = "rof_TZ";
const UZ_ARAB_AF = "uz-Arab_AF";
const VI_VN = "vi_VN";
const EN_MT = "en_MT";
const KW = "kw";
const YAV_CM = "yav_CM";
const TA_MY = "ta_MY";
const RU_KG = "ru_KG";
const KAB = "kab";
const KY = "ky";
const FF = "ff";
const EN_PG = "en_PG";
const TO_TO = "to_TO";
const AR_LY = "ar_LY";
const JGO = "jgo";
const EN_HU = "en_HU";
const AF_ZA = "af_ZA";
const EN_UG = "en_UG";
const DE_LI = "de_LI";
const FI = "fi";
const ES_SV = "es_SV";
const KHQ = "khq";
const GSW = "gsw";
const KSF_CM = "ksf_CM";
const FR_DJ = "fr_DJ";
const EN_MU = "en_MU";
const LN_CF = "ln_CF";
const KEA_CV = "kea_CV";
const PL_PL = "pl_PL";
const PA_ARAB = "pa-Arab";
const FR_MC = "fr_MC";
const SR_BA = "sr_BA";
const SR_LATN = "sr-Latn";
const EN_RU = "en_RU";
const EN_PH = "en_PH";
const SAQ = "saq";
const AR_PS = "ar_PS";
const FR_CD = "fr_CD";
const BEM_ZM = "bem_ZM";
const RU_RU = "ru_RU";
const EN_FI = "en_FI";
const FO = "fo";
const SO_KE = "so_KE";
const LN_CG = "ln_CG";
const AR_OM = "ar_OM";
const PT_ST = "pt_ST";
const EN_KI = "en_KI";
const KL_GL = "kl_GL";
const FR = "fr";
const ES_CR = "es_CR";
const SES_ML = "ses_ML";
const MER_KE = "mer_KE";
const XOG = "xog";
const XOG_UG = "xog_UG";
const NL_SX = "nl_SX";
const EN_FJ = "en_FJ";
const MS_BN = "ms_BN";
const EN_MW = "en_MW";
const AR_MA = "ar_MA";
const PT_MO = "pt_MO";
const KAM = "kam";
const EN_TC = "en_TC";
const AF = "af";
const AR_TN = "ar_TN";
const AM_ET = "am_ET";
const ES_PE = "es_PE";
const SBP_TZ = "sbp_TZ";
const FR_CF = "fr_CF";
const VUN_TZ = "vun_TZ";
const FR_RE = "fr_RE";
const AR_JO = "ar_JO";
const EBU = "ebu";
const LG = "lg";
const HA_NG = "ha_NG";
const LV_LV = "lv_LV";
const AK = "ak";
const CHR = "chr";
const AZ_CYRL_AZ = "az-Cyrl_AZ";
const DAV = "dav";
const EN_EE = "en_EE";
const ES_419 = "es_419";
const EBU_KE = "ebu_KE";
const EN_CY = "en_CY";
const FR_MF = "fr_MF";
const EN_AL = "en_AL";
const AM = "am";
const EN_PK = "en_PK";
const MGO_CM = "mgo_CM";
const FR_CG = "fr_CG";
const DJE = "dje";
const EN_JE = "en_JE";
const EN_LR = "en_LR";
const DYO = "dyo";
const LN = "ln";
const AK_GH = "ak_GH";
const PA_IN = "pa_IN";
const AR_DJ = "ar_DJ";
const EN_BS = "en_BS";
const LO = "lo";
const ZH_TW = "zh_TW";
const LG_UG = "lg_UG";
const AR_KW = "ar_KW";
const AR = "ar";
const BS_CYRL_BA = "bs-Cyrl_BA";
const ES_EA = "es_EA";
const FR_MG = "fr_MG";
const CA_ES = "ca_ES";
const AS = "as";
const HE_IL = "he_IL";
const ES_CU = "es_CU";
const EN_CZ = "en_CZ";
const EN_PL = "en_PL";
const FR_GA = "fr_GA";
const MG_MG = "mg_MG";
const FR_CH = "fr_CH";
const EN_LS = "en_LS";
const LT = "lt";
const MY_MM = "my_MM";
const KK_KZ = "kk_KZ";
const GA = "ga";
const EN_FM = "en_FM";
const LU = "lu";
const PS_AF = "ps_AF";
const NMG = "nmg";
const ES_BO = "es_BO";
const SBP = "sbp";
const LV = "lv";
const VUN = "vun";
const FR_YT = "fr_YT";
const KM_KH = "km_KH";
const TEO_UG = "teo_UG";
const FR_SN = "fr_SN";
const OM_ET = "om_ET";
const AR_ER = "ar_ER";
const GSW_CH = "gsw_CH";
const ES_PH = "es_PH";
const FI_FI = "fi_FI";
const TR_TR = "tr_TR";
const FR_CI = "fr_CI";
const EN_LT = "en_LT";
const EN_UM = "en_UM";
const UR_PK = "ur_PK";
const HR_HR = "hr_HR";
const NL_CW = "nl_CW";
const EN_KN = "en_KN";
const MS_MY = "ms_MY";
const AR_IL = "ar_IL";
const EN_ZM = "en_ZM";
const ES_EC = "es_EC";
const GL_ES = "gl_ES";
const EN_GU = "en_GU";
const GL = "gl";
const NMG_CM = "nmg_CM";
const ZH_MO = "zh_MO";
const EN_NA = "en_NA";
const HA_NE = "ha_NE";
const MT_MT = "mt_MT";
const RM = "rm";
const KW_GB = "kw_GB";
const ZH_SG = "zh_SG";
const RN = "rn";
const RO = "ro";
const RM_CH = "rm_CH";
const SAQ_KE = "saq_KE";
const VAI_LR = "vai_LR";
const KA_GE = "ka_GE";
const ES_GQ = "es_GQ";
const SR_LATN_RS = "sr-Latn_RS";
const EN_VU = "en_VU";
const ZH_HANS_HK = "zh-Hans_HK";
const EN_LV = "en_LV";
const AGQ = "agq";
const GU = "gu";
const LO_LA = "lo_LA";
const RU = "ru";
const EN_SB = "en_SB";
const GV = "gv";
const EN_BW = "en_BW";
const YAV = "yav";
const TA_SG = "ta_SG";
const FR_BE = "fr_BE";
const BG_BG = "bg_BG";
const ES_MX = "es_MX";
const RW = "rw";
const BE = "be";
const ND_ZW = "nd_ZW";
const KAB_DZ = "kab_DZ";
const MUA = "mua";
const PT_CV = "pt_CV";
const BG = "bg";
const TG_TJ = "tg_TJ";
const MS_SG = "ms_SG";
const MG = "mg";
const SG_CF = "sg_CF";
const PA_ARAB_PK = "pa-Arab_PK";
const SW_TZ = "sw_TZ";
const EN_SC = "en_SC";
const NUS = "nus";
const SHI_TFNG = "shi-Tfng";
const AR_QA = "ar_QA";
const NAQ_NA = "naq_NA";
const FR_BF = "fr_BF";
const RW_RW = "rw_RW";
const AS_IN = "as_IN";
const GUZ = "guz";
const KSB = "ksb";
const FR_ML = "fr_ML";
const MK = "mk";
const KOK_IN = "kok_IN";
const SQ_AL = "sq_AL";
const ML = "ml";
const FR_GF = "fr_GF";
const BM = "bm";
const LU_CD = "lu_CD";
const FR_CM = "fr_CM";
const BN = "bn";
const AR_LB = "ar_LB";
const ID_ID = "id_ID";
const UZ_ARAB = "uz-Arab";
const BO = "bo";
const EN_FR = "en_FR";
const EN_DE = "en_DE";
const VAI_LATN_L = "vai-Latn_L";
const AR_SO = "ar_SO";
const RU_BY = "ru_BY";

Methods

MagicObject\Util\PicoPasswordUtil

Declaration

class PicoPasswordUtil { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoPasswordUtil

A utility class for handling password management tasks, including validation, hashing, and enforcing security policies.

This class provides methods to validate passwords based on customizable rules, including minimum length and complexity requirements. It also offers functionality to hash passwords using various cryptographic algorithms to ensure secure storage.

Passwords can be validated against a regular expression that enforces specific character types (uppercase, lowercase, numbers, and special characters). Users can configure the minimum length and the hashing algorithm used to generate password hashes.

Example usage:

 $passwordUtil = new PicoPasswordUtil();
 $passwordUtil->validate('YourSecureP@ssw0rd!');
 $hashedPassword = $passwordUtil->getHash('YourSecureP@ssw0rd!');

Constants

const ALG_MD2 = "md2";
const ALG_MD4 = "md4";
const ALG_MD5 = "md5";
const ALG_SHA1 = "sha1";
const ALG_SHA224 = "sha224";
const ALG_SHA256 = "sha256";
const ALG_SHA384 = "sha384";
const ALG_SHA512_224 = "sha512/224";
const ALG_SHA512_256 = "sha512/256";
const ALG_SHA512 = "sha512";
const ALG_SHA3_224 = "sha3-224";
const ALG_SHA3_256 = "sha3-256";
const ALG_SHA3_384 = "sha3-384";
const ALG_SHA3_512 = "sha3-512";
const ALG_RIPEMD128 = "ripemd128";
const ALG_RIPEMD160 = "ripemd160";
const ALG_RIPEMD256 = "ripemd256";
const ALG_RIPEMD320 = "ripemd320";
const ALG_WHIRLPOOL = "whirlpool";
const ALG_TIGER128_3 = "tiger128,3";
const ALG_TIGER160_3 = "tiger160,3";
const ALG_TIGER192_3 = "tiger192,3";
const ALG_TIGER128_4 = "tiger128,4";
const ALG_TIGER160_4 = "tiger160,4";
const ALG_TIGER192_4 = "tiger192,4";
const ALG_SNEFRU = "snefru";
const ALG_SNEFRU256 = "snefru256";
const ALG_GOST = "gost";
const ALG_GOST_CRYPTO = "gost-crypto";
const ALG_ADLER32 = "adler32";
const ALG_CRC32 = "crc32";
const ALG_CRC32B = "crc32b";
const ALG_CRC32C = "crc32c";
const ALG_FNV132 = "fnv132";
const ALG_FNV1A32 = "fnv1a32";
const ALG_FNV164 = "fnv164";
const ALG_FNV1A64 = "fnv1a64";
const ALG_JOAAT = "joaat";
const ALG_HAVAL128_3 = "haval128,3";
const ALG_HAVAL160_3 = "haval160,3";
const ALG_HAVAL192_3 = "haval192,3";
const ALG_HAVAL224_3 = "haval224,3";
const ALG_HAVAL256_3 = "haval256,3";
const ALG_HAVAL128_4 = "haval128,4";
const ALG_HAVAL160_4 = "haval160,4";
const ALG_HAVAL192_4 = "haval192,4";
const ALG_HAVAL224_4 = "haval224,4";
const ALG_HAVAL256_4 = "haval256,4";
const ALG_HAVAL128_5 = "haval128,5";
const ALG_HAVAL160_5 = "haval160,5";
const ALG_HAVAL192_5 = "haval192,5";
const ALG_HAVAL224_5 = "haval224,5";
const ALG_HAVAL256_5 = "haval256,5";

Properties

1. regex

Declaration

private string $regex = '/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{%d,}$/';

Description

Regular expression format for password validation.

This regex is used to enforce complexity rules for passwords, including the presence of uppercase letters, lowercase letters, numbers, and special characters.

2. minLength

Declaration

private int $minLength = 8;

Description

Minimum length of the password.

This sets the minimum number of characters required for a valid password.

3. hashAlgorithm

Declaration

private string $hashAlgorithm = 'sha1';

Description

Hash algorithm to be used for password hashing.

This determines which hashing algorithm will be applied when generating password hashes.

Methods

1. __construct

Declaration

public function __construct(
    string|null $hashAlgorithm = null,
    int $minLength = 8,
    string|null $regex = null
)
{
}

Description

Constructor to initialize password utility settings.

Parameters

$hashAlgorithm

Optional hashing algorithm to use.

$minLength

Minimum length of the password. Default is 8.

$regex

Optional regex pattern for password validation.

2. getRegexString

Declaration

private function getRegexString() : string
{
}

Description

Get the regular expression string used for password validation.

The method replaces the placeholder '%d' with the minimum length defined for the password.

Return

string

The regex string with the minimum length.

3. validate

Declaration

public function validate(
    string $password
) : bool
{
}

Description

Validate the given password against the set rules.

This method checks if the password meets the length requirement and matches the defined complexity rules. Throws an exception if the password is invalid.

Parameters

$password

Password to be validated.

Return

bool

True if the password is valid.

Throws

InvalidInputFormatException

If the password is invalid.

4. getHash

Declaration

public function getHash(
    string $password,
    bool $binary = false,
    bool $validate = true
) : string
{
}

Description

Get the hash of the given plain text password.

This method hashes the password using the specified hashing algorithm. Optionally validates the password before hashing.

Parameters

$password

Plain text password to be hashed.

$binary

Optional. If true, returns the binary representation of the hash.

$validate

Optional. If true, validates the password before hashing.

Return

string

The resulting hashed password.

Throws

InvalidInputFormatException

If the password is invalid and validation is enabled.

5. getRegex

Declaration

public function getRegex() : string
{
}

Description

Get the current regular expression format used for password validation.

Return

string

The current regex format.

6. setRegex

Declaration

public function setRegex(
    string $regex
) : self
{
}

Description

Set a new regular expression format for password validation.

Parameters

$regex

New regular expression format.

Return

self

Returns the current instance for method chaining.

7. getMinLength

Declaration

public function getMinLength() : int
{
}

Description

Get the minimum length required for passwords.

Return

int

The minimum length for passwords.

8. setMinLength

Declaration

public function setMinLength(
    int $minLength
) : self
{
}

Description

Set a new minimum length requirement for passwords.

Parameters

$minLength

New minimum length for passwords.

Return

self

Returns the current instance for method chaining.

9. getHashAlgorithm

Declaration

public function getHashAlgorithm() : string
{
}

Description

Get the currently set hash algorithm.

Return

string

The hashing algorithm in use.

10. setHashAlgorithm

Declaration

public function setHashAlgorithm(
    string $hashAlgorithm
) : self
{
}

Description

Set a new hash algorithm to be used for password hashing.

Parameters

$hashAlgorithm

New hashing algorithm.

Return

self

Returns the current instance for method chaining.

MagicObject\Util\PicoStringUtil

Declaration

class PicoStringUtil { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoStringUtil

A utility class for performing various string manipulations and transformations.

This class provides static methods for converting between different string case formats (snake case, camel case, kebab case), validating string contents, and manipulating strings (trimming, checking for null/empty values, etc.).

The methods are designed to be used statically, allowing for convenient access without needing to instantiate the class.

Example usage:

 <?php
 $camelCase = PicoStringUtil::camelize('example_string');
 $kebabCase = PicoStringUtil::kebapize('exampleString');
 $isNotEmpty = PicoStringUtil::isNotNullAndNotEmpty('Some Value');

Methods

2. camelize

Declaration

public static function camelize(
    string $input,
    string $glue = '_'
) : string
{
}

Description

Convert snake case to camel case

Parameters

$input

Input string in snake case format.

$glue

Optional. The glue character used in the input string (default is '_').

Return

string

Converted string in camel case format.

3. upperCamelize

Declaration

public static function upperCamelize(
    string $input,
    string $glue = '_'
) : string
{
}

Description

Convert snake case to upper camel case

Parameters

$input

Input string in snake case format.

$glue

Optional. The glue character used in the input string (default is '_').

Return

string

Converted string in upper camel case format.

4. snakeize

Declaration

public static function snakeize(
    string $input,
    string $glue = '_'
) : string
{
}

Description

Convert camel case to snake case

Converts a string from camel case (e.g., exampleString) to snake case (e.g., example_string).

Parameters

$input

Input string in camel case format.

$glue

Optional. The glue character used in the input string (default is '_').

Return

string

Converted string in snake case format.

5. snakeizeObject

Declaration

public static function snakeizeObject(
    mixed $object
) : mixed
{
}

Description

Snakeize object

Converts all keys of an object or an array to snake case. This is useful for normalizing data structures when working with APIs or databases.

Parameters

$object

Object or array to be converted.

Return

mixed

The input object/array with keys converted to snake case.

6. snakeToTitle

Declaration

public static function snakeToTitle(
    string $input,
    string $glue = '_'
) : string
{
}

Description

Convert snake case to title case

Converts a snake case string (e.g., example_string) to title case (e.g., Example String). Words are separated by spaces, and the first letter of each word is capitalized.

Parameters

$input

Input string in snake case format.

$glue

Optional. The glue character used in the input string (default is '_').

Return

string

Converted string in title case format.

7. camelToTitle

Declaration

public static function camelToTitle(
    string $input
) : string
{
}

Description

Convert camel case to title case

Converts a camel case string (e.g., exampleString) to title case (e.g., Example String).

Parameters

$input

Input string in camel case format.

Return

string

Converted string in title case format.

8. kebapize

Declaration

public static function kebapize(
    string $input
) : string
{
}

Description

Convert to kebab case

Converts a string to kebab case (e.g., example_string becomes example-string). Useful for URL slugs or CSS class names.

Parameters

$input

Input string in any case format.

Return

string

Converted string in kebab case format.

9. constantKey

Declaration

public function constantKey(
    string $input
) : string
{
}

Description

Create constant key

Converts a string to a constant key format (e.g., example_string becomes EXAMPLE_STRING).

Parameters

$input

Input string in snake case format.

Return

string

Converted string in uppercase snake case format.

10. startsWith

Declaration

public static function startsWith(
    string $haystack,
    string $value,
    bool $caseSensitive = false
) : bool
{
}

Description

Check if string starts with a substring

Determines if the given string starts with the specified substring. Comparison can be case-sensitive or case-insensitive.

Parameters

$haystack

The string to check.

$value

The substring to look for at the start.

$caseSensitive

Optional. Flag to indicate if the comparison is case-sensitive (default is false).

Return

bool

True if the string starts with the substring, false otherwise.

11. endsWith

Declaration

public static function endsWith(
    string $haystack,
    string $value,
    bool $caseSensitive = false
) : bool
{
}

Description

Check if string ends with a substring

Determines if the given string ends with the specified substring. Comparison can be case-sensitive or case-insensitive.

Parameters

$haystack

The string to check.

$value

The substring to look for at the end.

$caseSensitive

Optional. Flag to indicate if the comparison is case-sensitive (default is false).

Return

bool

True if the string ends with the substring, false otherwise.

12. lTrim

Declaration

public static function lTrim(
    string $haystack,
    string $substring,
    int $count = -1
) : string
{
}

Description

Left trim a string

Trims the specified substring from the start of the string for a defined number of times. If count is -1, it trims until the substring no longer occurs at the start.

Parameters

$haystack

The string to trim.

$substring

The substring to trim from the start.

$count

Optional. Number of times to trim (default is -1).

Return

string

The trimmed string.

13. rTrim

Declaration

public static function rTrim(
    string $haystack,
    string $substring,
    int $count = -1
) : string
{
}

Description

Right trim a string

Trims the specified substring from the end of the string for a defined number of times. If count is -1, it trims until the substring no longer occurs at the end.

Parameters

$haystack

The string to trim.

$substring

The substring to trim from the end.

$count

Optional. Number of times to trim (default is -1).

Return

string

The trimmed string.

14. isNotNullAndNotEmpty

Declaration

public static function isNotNullAndNotEmpty(
    string $value
) : bool
{
}

Description

Check if string is not null and not empty

Determines if the given string is neither null nor empty.

Parameters

$value

The string to check.

Return

bool

True if the string is not null and not empty, false otherwise.

15. isNullOrEmpty

Declaration

public static function isNullOrEmpty(
    string $value
) : bool
{
}

Description

Check if string is null or empty

Determines if the given string is either null or empty.

Parameters

$value

The string to check.

Return

bool

True if the string is null or empty, false otherwise.

16. selectNotNull

Declaration

public static function selectNotNull(
    mixed $value1,
    mixed $value2
) : mixed
{
}

Description

Select not null value

Returns the first value that is not null from the two provided values.

Parameters

$value1

The first value to check.

$value2

The second value to check.

Return

mixed

The first non-null value.

17. windowsCariageReturn

Declaration

public static function windowsCariageReturn(
    string $input
) : string
{
}

Description

Fix carriage returns in a string

Normalizes line endings in a string to Windows-style carriage return line feed (CRLF).

Parameters

$input

The input string to fix.

Return

string

The modified string with normalized line endings.

18. wordChunk

Declaration

public static function wordChunk(
    string $input,
    int $length = 76,
    string $delimiter = ' '
) : string
{
}

Description

Splits a string into chunks of a specified length without breaking words.

This method ensures that words are not split between chunks, making it ideal for scenarios where maintaining the integrity of words is crucial. The chunks are separated by the specified delimiter.

Parameters

$input

The input string to be chunked.

$length

The maximum length of each chunk. Defaults to 76.

$delimiter

The delimiter to append between chunks. Defaults to "\n".

Return

string

The chunked string with the specified delimiter between chunks.

MagicObject\Util\PicoTableUtil

Declaration

class PicoTableUtil { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Utility class for handling DOM element operations related to tables.

This class provides methods for setting attributes, class names, and identity properties on DOM elements, as well as parsing attribute strings into associative arrays. It is designed to facilitate the management of table-related DOM elements within the MagicObject framework.

Methods

2. setClassList

Declaration

public static function setClassList(
    DOMElement $node,
    array $classList
) : DOMElement
{
}

Description

Set the class list for a DOMElement.

Parameters

$node

The DOM node to modify.

$classList

An array of class names to set.

Return

DOMElement

The modified DOM node.

3. setAttributes

Declaration

public static function setAttributes(
    DOMElement $node,
    array $annotationAttributes
) : DOMElement
{
}

Description

Set attributes for a DOMElement.

Parameters

$node

The DOM node to modify.

$annotationAttributes

An associative array of attributes to set.

Return

DOMElement

The modified DOM node.

4. setIdentity

Declaration

public static function setIdentity(
    DOMElement $node,
    PicoGenericObject $identity
) : DOMElement
{
}

Description

Set the identity for a DOMElement.

Parameters

$node

The DOM node to modify.

$identity

The identity object.

Return

DOMElement

The modified DOM node.

5. parseElementAttributes

Declaration

public static function parseElementAttributes(
    string $attributes
) : array
{
}

Description

Parse attributes from a string representation.

Parameters

$attributes

The string containing attributes.

Return

array

An associative array of parsed attributes.

Throws

InvalidParameterException

If the provided attributes is an array.

6. isValidClassName

Declaration

public static function isValidClassName(
    string $className
) : bool
{
}

Description

Validate the class name of a DOMElement.

Parameters

$className

The class name to validate.

Return

bool

True if the class name is valid, false otherwise.

MagicObject\Util\PicoTestValueUtil

Declaration

class PicoTestValueUtil { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoTestValueUtil

A utility class for managing return values based on specified conditions. This class allows you to set a return value and control whether it should be returned based on conditions. It is useful for testing and mocking scenarios where specific outputs are required based on input conditions.

Properties

1. returnValue

Declaration

private mixed $returnValue;

Description

Value to be returned.

2. condition

Declaration

private bool $condition;

Description

Condition for determining return value.

Methods

1. doReturn

Declaration

public function doReturn(
    mixed $returnValue
) : self|mixed
{
}

Description

Set a return value.

Parameters

$returnValue

The value to return based on the condition.

Return

self|mixed

Returns the return value if the condition is true; otherwise, returns the instance.

2. doReturnSelected

Declaration

public function doReturnSelected() : self|mixed
{
}

Description

Set return value to 'selected'.

Return

self|mixed

Returns 'selected' if the condition is true; otherwise, returns the instance.

3. doReturnAttributeSelected

Declaration

public function doReturnAttributeSelected() : self|mixed
{
}

Description

Set return value to ' selected=selected'.

Return

self|mixed

Returns ' selected=selected' if the condition is true; otherwise, returns the instance.

4. doReturnChecked

Declaration

public function doReturnChecked() : self|mixed
{
}

Description

Set return value to 'checked'.

Return

self|mixed

Returns 'checked' if the condition is true; otherwise, returns the instance.

5. doReturnAttributeChecked

Declaration

public function doReturnAttributeChecked() : self|mixed
{
}

Description

Set return value to ' checked=checked'.

Return

self|mixed

Returns ' checked=checked' if the condition is true; otherwise, returns the instance.

6. thenReturn

Declaration

public function thenReturn(
    mixed $returnValue
) : mixed|null
{
}

Description

Set a return value and determine if it should be returned.

Parameters

$returnValue

The value to return if the condition is true.

Return

mixed|null

Returns the return value if the condition is true; otherwise, returns null.

7. when

Declaration

public function when(
    bool $condition
) : self|mixed
{
}

Description

Set the condition for returning the value.

Parameters

$condition

The condition that determines the return value.

Return

self|mixed

Returns the return value if set and the condition is true; otherwise, returns the instance.

8. whenEquals

Declaration

public function whenEquals(
    mixed $param1,
    mixed $param2
) : self|mixed
{
}

Description

Set the condition based on equality of two parameters.

Parameters

$param1

The first parameter to compare.

$param2

The second parameter to compare.

Return

self|mixed

Returns the return value if set and the parameters are equal; otherwise, returns the instance.

MagicObject\Util\PicoYamlUtil

Declaration

class PicoYamlUtil { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class PicoYamlUtil

A utility class for handling YAML operations, including converting arrays to YAML strings and determining the depth of nested arrays.

This class is intended to be used statically and cannot be instantiated.

Methods

2. arrayDepth

Declaration

public static function arrayDepth(
    array $array
) : int
{
}

Description

Get the depth of a nested array.

This method recursively calculates how deep the given array is.

Example:

 <?php
 $array = [1, [2, [3, 4]]];
 $depth = PicoYamlUtil::arrayDepth($array); // Returns 3

Parameters

$array

The array to be checked for depth.

Return

int

The depth of the array. Returns 0 for non-array input, 1 for empty arrays.

3. dump

Declaration

public static function dump(
    mixed $input,
    int|null $inline,
    int $indent,
    int $flags
) : string
{
}

Description

Dumps a PHP value to a YAML string.

This method converts a PHP array (or other types) into a YAML-formatted string. It allows customization of the inline representation, indentation, and flags for serialization.

Example:

 <?php
 $data = ['name' => 'John', 'age' => 30];
 $yaml = PicoYamlUtil::dump($data, null, 4, 0);

Parameters

$input

The PHP value to be converted to YAML.

$inline

The level at which to switch to inline YAML.

$indent

The number of spaces to use for indentation of nested nodes.

$flags

A bit field of DUMP_* constants to customize the dumped YAML string.

Return

string

A YAML string representing the original PHP value.

4. parseFile

Declaration

public static function parseFile(
    string $file
) : mixed
{
}

Description

Parse a YAML file and return the parsed data.

This function loads a YAML file and returns the parsed content as an array or object depending on the configuration of the YAML parser.

Parameters

$file

The path to the YAML file that needs to be parsed.

Return

mixed

The parsed YAML data, typically as an array or object.

Throws

Exception

If the file cannot be loaded or parsed.

5. parse

Declaration

public static function parse(
    string $rawData
) : mixed
{
}

Description

Parse raw YAML data and return the parsed content.

This function loads a raw YAML string and returns the parsed content as an array or object.

Parameters

$rawData

The raw YAML string to be parsed.

Return

mixed

The parsed YAML data, typically as an array or object.

Throws

Exception

If the YAML string cannot be parsed.

MagicObject\Util\Spicy

Declaration

class Spicy { }

Authors

  1. Vlad Andersen <vlad.andersen@gmail.com>
  2. Chris Wanstrath <chris@ozmm.org>

Links

  1. https://github.com/mustangostang/spyc/

Description

Class Spicy

This class is a modification of the Spyc project. The purpose of this modification is to integrate the class with other projects that use Composer, making it easy to use without requiring additional dependencies or code duplication. Additionally, code smells have been fixed to ensure the code remains clean and understandable when using SonarLint, thereby avoiding confusion for users when debugging code errors.

Constants

const REMPTY = "' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '";

Properties

1. dumpForceQuotes

Declaration

private bool $dumpForceQuotes = false;

Description

If set to true, forces YAML dump to enclose any string value in quotes. False by default.

2. emptyHashAsObject

Declaration

private bool $emptyHashAsObject = false;

Description

If set to true, forces YAML load to use the syck_load function when possible. False by default.

3. _dumpIndent

Declaration

private int $_dumpIndent;

Description

Indentation level for dumping YAML.

4. _dumpWordWrap

Declaration

private int $_dumpWordWrap;

Description

Word wrap length for dumping YAML.

5. _containsGroupAnchor

Declaration

private bool $_containsGroupAnchor = false;

Description

Indicates if a group anchor is present in the YAML document.

6. _containsGroupAlias

Declaration

private bool $_containsGroupAlias = false;

Description

Indicates if a group alias is present in the YAML document.

7. path

Declaration

private mixed $path;

Description

Current path being processed in the YAML structure.

8. result

Declaration

private mixed $result;

Description

Result of the YAML parsing or dumping process.

9. literalPlaceHolder

Declaration

private string $literalPlaceHolder = '___YAML_Literal_Block___';

Description

Placeholder for YAML literal blocks.

10. savedGroups

Declaration

private array $savedGroups = array();

Description

List of saved groups encountered during YAML parsing.

11. indent

Declaration

private int $indent;

Description

Current indentation level during parsing or dumping.

12. delayedPath

Declaration

private array $delayedPath = array();

Description

Path modifier to be applied after adding the current element.

Methods

1. load

Declaration

public function load(
    string $input
) : array
{
}

Description

Load a valid YAML string to Spicy.

Parameters

$input

Return

array
2. loadFile

Declaration

public function loadFile(
    string $input,
    array $options = array ( )
) : array
{
}

Description

Load a YAML file or string and convert it into a PHP array.

This method accepts a file path or a string containing YAML content and converts it into a PHP array. Options can be set to customize the behavior.

Parameters

$input

Path to the YAML file or a string containing YAML content.

$options

Optional settings to modify parsing behavior.

Return

array

The parsed YAML converted to a PHP array.

3. loadString

Declaration

public function loadString(
    string $input,
    array $options = array ( )
) : array
{
}

Description

Load a YAML string and convert it into a PHP array.

This method accepts a string containing YAML content and converts it into a PHP array. Options can be set to customize the behavior.

Parameters

$input

String containing YAML content.

$options

Optional settings to modify parsing behavior.

Return

array

The parsed YAML converted to a PHP array.

4. dump

Declaration

public function dump(
    array $array,
    int $indent = false,
    int $wordwrap = false,
    bool $noOpeningDashes = false
) : string
{
}

Description

Convert a PHP array to a YAML string.

This method converts a PHP array into a YAML string. You can customize the indentation and word wrapping. If not provided, the default values for indentation and word wrapping are 2 spaces and 40 characters, respectively.

Parameters

$array

The PHP array to be converted.

$indent

Indentation size. Default is 2 spaces. Pass false to use the default.

$wordwrap

Word wrap limit. Default is 40 characters. Pass 0 for no word wrap.

$noOpeningDashes

Whether to omit the opening dashes (---) from the YAML. Default is false.

Return

string

The YAML representation of the provided PHP array.

5. _yamlize

Declaration

private function _yamlize(
    mixed $key,
    mixed $value,
    int $indent,
    int $previousKey = -1,
    int $firstKey = 0,
    array|null $sourceArray = null
) : string
{
}

Description

Converts a key-value pair to a YAML string.

This method attempts to convert a key and its corresponding value into a YAML-formatted string. It recursively processes arrays and objects.

Parameters

$key

The key name.

$value

The value associated with the key.

$indent

The current indentation level.

$previousKey

The previous key in the array (used for sequences).

$firstKey

The first key in the current array.

$sourceArray

The source array being processed.

Return

string

The YAML representation of the key-value pair.

6. _yamlizeArray

Declaration

private function _yamlizeArray(
    array $array,
    int $indent
) : string
{
}

Description

Converts an array to a YAML string with proper indentation.

This method iterates over an array and recursively converts each element into a YAML-formatted string.

Parameters

$array

The array to be converted.

$indent

The current indentation level.

Return

string

The YAML representation of the array.

7. _dumpNode

Declaration

private function _dumpNode(
    mixed $key,
    mixed $value,
    int $indent,
    int $previousKey = -1,
    int $firstKey = 0,
    array|null $sourceArray = null
) : string
{
}

Description

Converts a key-value pair to a YAML node string.

This method formats a key-value pair into a valid YAML node, applying literal blocks, folding, or quoting when necessary.

Parameters

$key

The key name.

$value

The value associated with the key.

$indent

The current indentation level.

$previousKey

The previous key in the array (used for sequences).

$firstKey

The first key in the current array.

$sourceArray

The source array being processed.

Return

string

The YAML representation of the key-value pair as a node.

8. _doLiteralBlock

Declaration

private function _doLiteralBlock(
    string $value,
    int $indent
) : string
{
}

Description

Creates a literal block for a YAML dump.

This method formats a given string as a YAML literal block, adding indentation and handling special characters or line breaks appropriately.

Parameters

$value

The string to be converted into a literal block.

$indent

The current indentation level.

Return

string

The YAML-formatted literal block.

9. _doFolding

Declaration

private function _doFolding(
    string $value,
    int $indent
) : string
{
}

Description

Folds a string of text if it exceeds the configured word wrap length.

This method wraps long strings in YAML using a folded style (>). If the word wrap is disabled (set to 0), it returns the string as is.

Parameters

$value

The string to be folded.

$indent

The current indentation level.

Return

string

The folded YAML string.

10. isTrueWord

Declaration

private function isTrueWord(
    string $value
) : bool
{
}

Description

Checks if a value represents a "true" word in YAML.

Recognized words: 'true', 'on', 'yes', 'y'.

Parameters

$value

The value to check.

Return

bool

True if the value matches a "true" word.

11. isFalseWord

Declaration

private function isFalseWord(
    string $value
) : bool
{
}

Description

Checks if a value represents a "false" word in YAML.

Recognized words: 'false', 'off', 'no', 'n'.

Parameters

$value

The value to check.

Return

bool

True if the value matches a "false" word.

12. isNullWord

Declaration

private function isNullWord(
    string $value
) : bool
{
}

Description

Checks if a value represents a "null" word in YAML.

Recognized words: 'null', '~'.

Parameters

$value

The value to check.

Return

bool

True if the value matches a "null" word.

13. isTranslationWord

Declaration

private function isTranslationWord(
    string $value
) : bool
{
}

Description

Checks if a value is a special YAML translation word.

This method checks if the value represents a "true", "false", or "null" word.

Parameters

$value

The value to check.

Return

bool

True if the value is a recognized YAML translation word.

14. coerceValue

Declaration

private function coerceValue(
    mixed
)
{
}

Description

Coerce a string into a native PHP type (boolean, null).

Based on the YAML 1.1 specification for boolean and null values. Reference: http://yaml.org/type/bool.html

Parameters

&$value

The value to coerce.

15. getTranslations

Declaration

private static function getTranslations(
    array $words
) : array
{
}

Description

Translates a set of words into multiple cases (lowercase, uppercase, capitalized).

This ensures compatibility with YAML 1.1 coercion rules, which allow for different case variations of certain keywords (e.g., 'True', 'TRUE', 'true').

Parameters

$words

The words to translate.

Return

array

An array of translated words with all case variations.

16. _loadFile

Declaration

private function _loadFile(
    string $input
) : array
{
}

Description

Loads a YAML file from the given path.

Parameters

$input

The file path.

Return

array

The parsed YAML data.

Throws

YamlException

If the file is not found.

17. _loadString

Declaration

private function _loadString(
    string $input
) : array
{
}

Description

Loads a YAML string and parses it into an array.

Parameters

$input

The YAML string.

Return

array

The parsed YAML data.

18. loadWithSource

Declaration

private function loadWithSource(
    array $source
) : array
{
}

Description

Processes a source array of lines and converts it to a PHP array.

Parameters

$source

The source lines.

Return

array

The parsed result as an associative array.

19. loadFromString

Declaration

private function loadFromString(
    string $input
) : array
{
}

Description

Converts a YAML string into an array of lines, removing any trailing carriage returns.

Parameters

$input

The YAML string.

Return

array

An array of lines from the YAML input.

20. fixRaw

Declaration

private function fixRaw(
    string $text
) : string
{
}

Description

Fixes raw YAML input by ensuring proper formatting for list items (- key:) to avoid indentation issues or malformed structures in the YAML.

The method scans each line and, if it detects a list item (- key:), it re-adjusts the line's indentation to ensure it aligns correctly with the rest of the document.

Parameters

$text

The raw YAML input string.

Return

string

The formatted YAML string with adjusted indentation for list items.

21. _parseLine

Declaration

private function _parseLine(
    string $line
) : array
{
}

Description

Parses a single line of YAML and returns the appropriate PHP structure for it.

This method determines the type of the line (mapped sequence, mapped value, array element, etc.) and converts it into a structured array representation.

Parameters

$line

A single line from the YAML input.

Return

array

The parsed representation of the line.

22. _toType

Declaration

private function _toType(
    string $value
) : mixed
{
}

Description

Converts a YAML value string into the appropriate PHP type.

Supports scalar values (strings, integers, floats, booleans, null), arrays, and objects. Handles quoted strings, inline mappings ({}), and inline sequences ([]).

Parameters

$value

The YAML value to convert.

Return

mixed

The converted value as a native PHP type.

23. _inlineEscape

Declaration

private function _inlineEscape(
    string $inline
) : array
{
}

Description

Parses an inline YAML string and splits it into an array of elements.

Handles inline sequences ([]), mappings ({}), quoted strings, and empty strings, ensuring they are correctly parsed without being broken by commas or special characters.

Parameters

$inline

The inline YAML string.

Return

array

Parsed components as an array.

24. literalBlockContinues

Declaration

private function literalBlockContinues(
    string $line,
    int $lineIndent
) : bool
{
}

Description

Checks if a literal block should continue on the next line.

A literal block continues if the current line is blank or if it is more indented than the block's initial indentation level.

Parameters

$line

The current line being processed.

$lineIndent

The initial indentation level of the block.

Return

bool

Returns true if the literal block should continue; otherwise, false.

25. referenceContentsByAlias

Declaration

private function referenceContentsByAlias(
    string $alias
) : mixed
{
}

Description

Retrieves the value of a YAML reference (alias).

The method looks up the alias in the saved groups and traverses the result array using the group path to return the associated value.

Parameters

$alias

The alias name to look up.

Return

mixed

The value associated with the alias, or null if not found.

Throws

Exception

If the alias is not found in the saved groups.

26. addArrayInline

Declaration

private function addArrayInline(
    array $array,
    int $indent
) : bool
{
}

Description

Adds an array to the current path in an inline manner.

This method is used to add multiple key-value pairs from the given array at the specified indentation level while maintaining the current path.

Parameters

$array

The array to add.

$indent

The current indentation level.

Return

bool

Returns true if the array was added; otherwise, false.

27. addArray

Declaration

private function addArray(
    array $incomingData,
    int $incomingIndent
) : $this
{
}

Description

Adds an array to the result at the specified indentation level.

This method processes incoming data and integrates it into the result array based on the current path and indentation. It also handles YAML anchors and aliases.

Parameters

$incomingData

The data to be added.

$incomingIndent

The indentation level of the incoming data.

Return

$this

Returns the current instance for method chaining.

28. startsLiteralBlock

Declaration

private static function startsLiteralBlock(
    string $line
) : string|false
{
}

Description

Check if the line starts a literal block.

This function checks if the line ends with a literal block indicator, either | or >. It also excludes lines that contain HTML tags.

Parameters

$line

The line to check.

Return

string|false

Returns | or > if it starts a literal block, false otherwise.

29. greedilyNeedNextLine

Declaration

private static function greedilyNeedNextLine(
    string $line
) : bool
{
}

Description

Check if the next line is needed to complete the current one.

This function determines whether a following line is required to complete a structure, for instance when the line starts an array or contains a reference to one.

Parameters

$line

The line to analyze.

Return

bool

Returns true if the next line is needed, false otherwise.

30. addLiteralLine

Declaration

private function addLiteralLine(
    string $literalBlock,
    string $line,
    string $literalBlockStyle,
    int $indent = -1
) : string
{
}

Description

Add a literal line to a literal block.

This function appends a line to the literal block. It handles indentation and adjusts the line's content according to the specified literal block style (| or >).

Parameters

$literalBlock

The existing literal block content.

$line

The line to add.

$literalBlockStyle

The style of the literal block (| or >).

$indent

The indentation level to strip from the line (default: -1).

Return

string

The updated literal block with the added line.

31. revertLiteralPlaceHolder

Declaration

public function revertLiteralPlaceHolder(
    array $lineArray,
    string $literalBlock
) : array
{
}

Description

Revert literal placeholders back to the full literal block.

This function searches for literal placeholders in the provided lines and replaces them with the actual content of the literal block.

Parameters

$lineArray

The array of lines to process.

$literalBlock

The literal block content to insert.

Return

array

The updated line array with placeholders replaced.

32. stripIndent

Declaration

private static function stripIndent(
    string $line,
    int $indent = -1
) : string
{
}

Description

Strip indentation from a line.

This function removes leading whitespace from a line based on the provided indentation level.

Parameters

$line

The line to strip.

$indent

The number of spaces to strip (default: -1).

Return

string

The line with indentation removed.

33. getParentPathByIndent

Declaration

private function getParentPathByIndent(
    int $indent
) : array
{
}

Description

Get the parent path for a given indentation level.

This function retrieves the path of the parent nodes based on the current indentation level.

Parameters

$indent

The current indentation level.

Return

array

The parent path for the given indentation level.

34. isComment

Declaration

private static function isComment(
    string $line
) : bool
{
}

Description

Check if the line is a comment.

This function checks if a line is a comment, either starting with a # symbol or containing a YAML document separator (---).

Parameters

$line

The line to check.

Return

bool

Returns true if the line is a comment, false otherwise.

35. isEmpty

Declaration

private static function isEmpty(
    string $line
) : bool
{
}

Description

Check if the line is empty.

This function checks if a line is empty after trimming leading and trailing whitespace.

Parameters

$line

The line to check.

Return

bool

Returns true if the line is empty, false otherwise.

36. isArrayElement

Declaration

private function isArrayElement(
    string $line
) : bool
{
}

Description

Check if the line is an array element.

This function checks if a line starts with a dash (-), which is indicative of an element in a YAML array.

Parameters

$line

The line to check.

Return

bool

Returns true if the line is an array element, false otherwise.

37. unquote

Declaration

private static function unquote(
    string $value
) : string
{
}

Description

Remove quotes from a value.

This function removes single or double quotes from the start and end of a string, if present.

Parameters

$value

The value to unquote.

Return

string

The value without quotes.

38. startsMappedSequence

Declaration

private function startsMappedSequence(
    string $line
) : bool
{
}

Description

Check if the line starts a mapped sequence.

This function checks if a line represents the start of a mapped sequence, indicated by a - followed by a key and a colon (:).

Parameters

$line

The line to check.

Return

bool

Returns true if the line starts a mapped sequence, false otherwise.

39. returnMappedSequence

Declaration

private function returnMappedSequence(
    string $line
) : array
{
}

Description

Return the mapped sequence from a line.

This function processes the line to extract the key and create a corresponding array for a mapped sequence.

Parameters

$line

The line to process.

Return

array

The array representing the mapped sequence.

40. checkKeysInValue

Declaration

private function checkKeysInValue(
    string $value
)
{
}

Description

Check if a value contains multiple keys.

This function checks if the value contains more than one key, indicated by the presence of a colon (:) in a non-array or non-object structure.

Parameters

$value

The value to check.

Throws

YamlException

If there are too many keys in the value.

41. returnMappedValue

Declaration

private function returnMappedValue(
    string $line
) : array
{
}

Description

Return a mapped value from a line.

This function processes the line and returns a key-value pair for a mapped value.

Parameters

$line

The line to process.

Return

array

The array with the key-value pair.

42. startsMappedValue

Declaration

private function startsMappedValue(
    string $line
) : bool
{
}

Description

Check if the line represents a mapped value (ends with a colon).

This function checks whether the line ends with a colon (:), indicating that it is likely a mapped value in the YAML format.

Parameters

$line

The line of text to check.

Return

bool

Returns true if the line ends with a colon, false otherwise.

43. isPlainArray

Declaration

private function isPlainArray(
    string $line
) : bool
{
}

Description

Check if the line represents a plain array.

This function checks whether the line starts with an opening bracket ([) and ends with a closing bracket (]), which is characteristic of a plain array in YAML.

Parameters

$line

The line of text to check.

Return

bool

Returns true if the line is a plain array, false otherwise.

44. returnPlainArray

Declaration

private function returnPlainArray(
    string $line
) : mixed
{
}

Description

Return the parsed value of a plain array.

This function processes the line and converts it to its appropriate data type based on the provided method _toType.

Parameters

$line

The line representing the array element to be processed.

Return

mixed

The parsed value after conversion using _toType.

45. returnKeyValuePair

Declaration

private function returnKeyValuePair(
    string $line
) : array
{
}

Description

Return a key-value pair from a line.

This function extracts a key-value pair from a line. It handles cases where the key is wrapped in quotes and also checks for special cases like 0 as key. The value is processed to determine its data type.

Parameters

$line

The line to parse.

Return

array

Returns an associative array with the key and value.

46. returnArrayElement

Declaration

private function returnArrayElement(
    string $line
) : array
{
}

Description

Return an array element from the line.

This function processes the line and trims the first character (usually a dash) before converting it to its appropriate type. It also checks if the value is an array and recursively handles nested elements.

Parameters

$line

The line to process.

Return

array

Returns an array with the processed value.

47. nodeContainsGroup

Declaration

private function nodeContainsGroup(
    string $line
) : string|false
{
}

Description

Check if the line contains a group anchor or alias.

This function checks if a line contains a reference to a group anchor (denoted by &) or alias (denoted by *). It can match anchors or aliases at the beginning or end of the line, as well as inline references such as <<.

Parameters

$line

The line to check for group anchors or aliases.

Return

string|false

Returns the group reference (anchor or alias) if found,

48. addGroup

Declaration

private function addGroup(
    string $line,
    string $group
) : void
{
}

Description

Add a group anchor or alias to the internal properties.

This function processes a group identifier (anchor or alias) and stores it in the appropriate internal property, depending on whether it's an anchor ('&') or an alias ('*').

Parameters

$line

The current line being processed (unused in this method).

$group

The group string which can be an anchor or alias.

Return

void
49. stripGroup

Declaration

private function stripGroup(
    string $line,
    string $group
) : string
{
}

Description

Strip a group identifier from a line of text.

This function removes the specified group identifier (anchor or alias) from the line and trims any extra spaces from the result.

Parameters

$line

The line of text to process.

$group

The group identifier to remove from the line.

Return

string

The line with the group identifier removed and trimmed.

50. getDumpForceQuotes

Declaration

public function getDumpForceQuotes() : bool
{
}

Description

Get the flag determining whether quotes are forced in the dump.

By default, the value is false. This flag indicates whether strings should always be wrapped in quotes during the dumping process.

Return

bool

The current setting of the flag for forced quotes.

51. setDumpForceQuotes

Declaration

public function setDumpForceQuotes(
    bool $dumpForceQuotes
) : self
{
}

Description

Set the flag for forcing quotes in the dump.

This function allows you to specify whether strings should always be enclosed in quotes during the dumping process.

Parameters

$dumpForceQuotes

The value indicating whether to force quotes

Return

self

The current instance to allow method chaining.

52. getEmptyHashAsObject

Declaration

public function getEmptyHashAsObject() : bool
{
}

Description

Get the flag determining whether empty hashes are treated as objects.

By default, this value is false. This flag specifies whether empty hash structures should be interpreted as objects instead of arrays.

Return

bool

The current setting of the flag for empty hash as object.

53. setEmptyHashAsObject

Declaration

public function setEmptyHashAsObject(
    bool $emptyHashAsObject
) : self
{
}

Description

Set the flag for treating empty hashes as objects.

This function allows you to specify whether empty hash structures should be considered as objects (true) or as empty arrays (false).

Parameters

$emptyHashAsObject

The value to indicate whether empty hashes

Return

self

The current instance to allow method chaining.

MagicObject\Util\TextConverter

Declaration

class TextConverter { }

Package

MagicObject\Util

Authors

  1. Kamshory

Links

  1. https://github.com/Planetbiru/MagicObject

Description

Class TextConverter

Converts text from one character encoding to another, specifically from ISO-8859-2 to UTF-8. This class handles character mappings for special characters and provides functionality for decoding HTML entities.

Properties

1. encodingFrom

Declaration

private $encodingFrom = 'ISO-8859-2';

Description

@var string $encodingFrom The source encoding (default is ISO-8859-2).

2. encodingTo

Declaration

private $encodingTo = 'UTF-8';

Description

@var string $encodingTo The target encoding (default is UTF-8).

3. mapChrChr

Declaration

private $mapChrChr = array ( 138 => 169, 140 => 166, 141 => 171, 142 => 174, 143 => 172, 156 => 182, 157 => 187, 161 => 183, 165 => 161, 188 => 165, 159 => 188, 185 => 177, 154 => 185, 190 => 181, 158 => 190, );

Description

@var array $mapChrChr Mapping of character codes to corresponding character codes.

4. mapChrString

Declaration

private $mapChrString = array ( 128 => '&euro;', 130 => '&sbquo;', 132 => '&bdquo;', 133 => '&hellip;', 134 => '&dagger;', 135 => '&Dagger;', 137 => '&permil;', 139 => '&lsaquo;', 145 => '&lsquo;', 146 => '&rsquo;', 147 => '&ldquo;', 148 => '&rdquo;', 149 => '&bull;', 150 => '&ndash;', 151 => '&mdash;', 153 => '&trade;', 155 => '&rsquo;', 166 => '&brvbar;', 169 => '&copy;', 171 => '&laquo;', 174 => '&reg;', 177 => '&plusmn;', 181 => '&micro;', 182 => '&para;', 183 => '&middot;', 187 => '&raquo;', );

Description

@var array $mapChrString Mapping of character codes to HTML entities.

Methods

1. __construct

Declaration

public function __construct(
    string|null $encodingFrom = null,
    string|null $encodingTo = null
)
{
}

Description

TextConverter constructor.

Initializes the encoding settings.

Parameters

$encodingFrom

The source encoding (default is ISO-8859-2).

$encodingTo

The target encoding (default is UTF-8).

2. execute

Declaration

public function execute(
    string $text
) : string
{
}

Description

Converts the given text from the source encoding to the target encoding.

Parameters

$text

The input text to be converted.

Return

string

The converted text.

3. prepareMap

Declaration

private function prepareMap() : array
{
}

Description

Prepares a mapping of characters based on the defined character mappings.

Return

array

The prepared character mapping array.

4. arrayMapAssoc

Declaration

private function arrayMapAssoc(
    callable $function,
    array $array
) : array
{
}

Description

Maps an associative array using a callback function.

Parameters

$function

The callback function to apply to each element.

$array

The array to be mapped.

Return

array

The resulting array after mapping.

MagicObject\Util\WS\PicoWebsocketClient

Declaration

class PicoWebsocketClient { }

Description

WebSocket client.

By Paragi 2013, Simon Riget MIT license. This is a demonstration of a WebSocket client. If you find flaws in it, please let me know at simon.riget (at) gmail.

WebSockets use hybi10 frame encoding:

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-------+-+-------------+-------------------------------+
   |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
   |I|S|S|S|  (4)  |A|     (7)     |             (16/63)           |
   |N|V|V|V|       |S|             |   (if payload len == 126/127) |
   | |1|2|3|       |K|             |                               |
   +-+-+-+-+-------+-+-------------+-------------------------------+
   |     Extended payload length continued, if payload len == 127  |
   +---------------------------------------------------------------+
   |                               |Masking-key, if MASK set to 1  |
   +-------------------------------+-------------------------------+
   | Masking-key (continued)       |          Payload Data         |
   +-------------------------------- - - - - - - - - - - - - - - - +
   :                     Payload Data continued ...                :
   + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
   |                     Payload Data continued ...                |
   +---------------------------------------------------------------+

See: https://tools.ietf.org/rfc/rfc6455.txt or: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10#section-4.2

Open WebSocket connection:

resource websocketOpen(string $host [,int $port [,array $headers [,string &$error_string [,int $timeout]]]])

Parameters

$host

The host URL. It can be a domain name like www.example.com or an IP address, with port number. Local host example: 127.0.0.1:8080.

$port

(Optional) The port number.

$headers

(Optional) Additional HTTP headers to attach to the request. For example, to parse a session cookie: "Cookie: SID=" . session_id().

&$error_string

(Optional) A referenced variable to store error messages, if any.

$timeout

(Optional) The maximum time in seconds that a read operation will wait for an answer from the server. Default value is 10 seconds.

$ssl

(Optional) Whether to use SSL for the connection. Default is false.

$persistant

(Optional) Whether to use a persistent connection. Default is false.

$path

(Optional) The path to connect to on the server. Default is '/'.

$context

(Optional) A stream context resource to be used for the connection.

Return

resource|false

Returns the WebSocket resource on success, or false on failure.

Methods

1. websocketOpen

Declaration

public static function websocketOpen(
    string $host = '',
    int $port = 80,
    array $headers = array ( ),
    string,
    int $timeout = 10,
    bool $ssl = false,
    bool $persistant = false,
    string $path = '/',
    resource|null $context = null
) : resource|false
{
}

Description

Opens a WebSocket connection.

This method initiates a WebSocket connection to the specified host and port by sending an HTTP GET request with an upgrade header. If the server accepts the connection, it will respond with a 101 status code indicating the upgrade.

Parameters

$host

The host URL (domain or IP address). Example: 'www.example.com'.

$port

The port number. Defaults to 80 for HTTP and 443 for HTTPS.

$headers

Optional additional HTTP headers to include in the request.

&$error_string

Reference to a variable that will store error messages, if any.

$timeout

The maximum time (in seconds) to wait for a server response. Defaults to 10.

$ssl

Whether to use SSL for the connection. Defaults to false.

$persistant

Whether to use a persistent connection. Defaults to false.

$path

The path to connect to on the server. Defaults to '/'.

$context

A stream context resource to be used for the connection.

Return

resource|false

Returns the WebSocket resource on success, or false on failure.

2. websocketWrite

Declaration

public static function websocketWrite(
    resource $sp,
    string $data,
    bool $final = true
) : int|false
{
}

Description

Sends a message through the WebSocket connection.

This method encodes the provided data into a WebSocket frame and sends it to the server.

Parameters

$sp

The WebSocket resource returned by websocketOpen.

$data

The data to send to the server.

$final

Indicates whether this is the final fragment of data. Defaults to true.

Return

int|false

The number of bytes written on success, or false on failure.

3. websocketWrite2

Declaration

public static function websocketWrite2(
    resource $sp,
    string $data,
    bool $final = true
) : int|false
{
}

Description

Sends a WebSocket message through the specified socket.

Parameters

$sp

The socket resource to write to.

$data

The data to send.

$final

Indicates whether this is the final fragment.

Return

int|false

The number of bytes written, or false on failure.

4. websocketRead

Declaration

public static function websocketRead(
    resource $sp,
    string|null,
    string|null
) : string|false
{
}

Description

Reads a message from the WebSocket connection.

This method reads a chunk of data from the server, handling the decoding of the WebSocket frame. It waits for the final chunk of data before returning.

Parameters

$sp

The WebSocket resource returned by websocketOpen.

&$errorCode

Reference to a variable that will store an error code, if any.

&$errorString

Reference to a variable that will store an error message, if any.

Return

string|false

The received data on success, or false on failure.

5. hybi10Decode

Declaration

public static function hybi10Decode(
    string $data
) : string
{
}

Description

Decodes a HyBi 10 WebSocket frame.

This method extracts and decodes the payload from a WebSocket frame according to the HyBi 10 specification. It handles masking if the frame is masked and supports both short and long payload lengths.

Parameters

$data

The frame data to decode, typically received from the WebSocket.

Return

string

The decoded payload data. If the frame is not a valid WebSocket frame,

6. getFrameHead0

Declaration

private static function getFrameHead0(
    string $type
) : int
{
}

Description

Gets the frame header byte for the specified frame type.

This method returns the appropriate header byte for different WebSocket frame types based on the HyBi 10 protocol. The frame header determines how the WebSocket payload is treated during transmission.

Parameters

$type

The type of frame. Acceptable values are:

Return

int

The frame header byte corresponding to the specified type.

7. hybi10Encode

Declaration

public static function hybi10Encode(
    string $payload,
    string $type = 'text',
    bool $masked = true
) : string|false
{
}

Description

Encodes the payload into a HyBi 10 WebSocket frame.

Parameters

$payload

The payload data to encode.

$type

The type of frame (e.g., 'text', 'close', 'ping', 'pong'). Defaults to 'text'.

$masked

Whether to mask the payload. Defaults to true.

Return

string|false

The encoded WebSocket frame on success, or false on failure.